-1

So for input:

arrondissement d

I Should get output:

Arrondissement de Boulogne-sur-Mer
Arrondissement Den Bosch

So it should give back both results. So in below code I've capitalized every first character of the word but this isn't correct because some words do not start with an upper case.

public ArrayList<City> getAllCitiesThatStartWithLetters(String letters) {
    ArrayList<City> filteredCities = new ArrayList<>();

    if (mCities != null) {
        for (City city : mCities) {
            if (city.getName().startsWith(new capitalize(letters))) {
                filteredCities.add(city);
            }
        }
    }
    return filteredCities;
}

public String capitalize(String capString){
    StringBuffer capBuffer = new StringBuffer();
    Matcher capMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(capString);
    while (capMatcher.find()){
        capMatcher.appendReplacement(capBuffer, capMatcher.group(1).toUpperCase() + capMatcher.group(2).toLowerCase());
    }

    return capMatcher.appendTail(capBuffer).toString();
}
Jim Clermonts
  • 1,694
  • 8
  • 39
  • 94
  • I think you are reinventing the wheel, this problem could be solved in like on line of code. Use the ``String``'s build in functions – Schidu Luca Mar 14 '18 at 12:40

4 Answers4

3

String has a very useful regionMatches method with an ignoreCase parameter, so you can check if a region of a string matches another string case insensitively.

String alpha = "My String Has Some Capitals";
String beta = "my string";
if (alpha.regionMatches(true, 0, beta, 0, beta.length())) {
    System.out.println("It matches");
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
1

You can use apache String utils:

import org.apache.commons.lang.StringUtils;
...
StringUtils.startsWithIgnoreCase(city.getName(), letters)
Maciej
  • 1,954
  • 10
  • 14
0

You can use String::matches with this regex (?i)searchWord.* not the (?i) which mean case-insensitive :

String searchWord = "arrondissement d";
String regex = "(?i)" + Pattern.quote(searchWord) + ".*";

boolean check1 = "Arrondissement de Boulogne-sur-Mer".matches(regex);  //true
boolean check2 = "Arrondissement Den Bosch".matches(regex);            //true

I used Use Pattern::quote to escape the special characters in your input.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

Instead of using a regex for your comparison, use the String.toLowerCase() so that both strings will be in lowercase, removing the need to account for upper-case values. use String.split(" ") to turn your phrase into an array of strings, and you will easily be able to turn the first character of each index into an upper-case letter. Re-combine your array of strings to form your phrase, and there you have it.

jmarkmurphy
  • 11,030
  • 31
  • 59
Chris Phillips
  • 1,997
  • 2
  • 19
  • 34