Search code examples
javastring-search

Getting phrases which have each word starting with an uppercase character


Currently i have tried getting words that start with an upper case in a sentence using Character.isUpperCase. However now i would like to only retrieve phrases in a sentence where all the 1st letter in every word of the phrase is upper case. How should i go about doing it.

E.g "This is a sample sentence so that Ang Mo Kio Avenue 1 is part of Ang Mo Kio."

I would retrieve "Ang Mo Kio Avenue 1" and "Ang Mo Kio".

String s = "This is a sample sentence so that Ang Mo Kio Avenue 1 is part of Ang Mo Kio.";
String[] words = s.split("[^a-zA-Z']+");
for (int i = 0; i < words.length; i++) {
  if (Character.isUpperCase(words[i].charAt(0))) {
  System.out.println(words[i]);
}}

The real intention is to extract 3 or more uppercase words, optionally followed by a number


Solution

  • i would like to only retrieve phrases in a sentence where all the 1st letter in every word of the phrase is upper case

    For that you need to capture consecutive upper case words, and append them in StringBuilder. If lowercase letter come then initialize StringBuilder.

    Try,

    StringBuilder answer = new StringBuilder();
    String s
     = "This is a sample sentence so that Ang Mo Kio Avenue 1 is part of Ang Mo Kio.";
        String[] words = s.split("\\s+");
        int count=0;
        for (int i = 0; i < words.length; i++) {
            char firstChar=words[i].charAt(0);
            if (Character.isUpperCase(firstChar) 
                     ||(count>0  && Character.isDigit(firstChar))) {
                answer.append(" "+words[i]);
                count++;
            } else {
                //To avoid less than 3 word apply this logic.
                if(count>2){
                System.out.println(answer);
                }
                count=0;
                answer = new StringBuilder();
            }
        }
        System.out.println(answer);// Also need to print answer here.
    

    Output:

     Ang Mo Kio Avenue 1
     Ang Mo Kio.