Pages

Problem Statement
Write a program that will accept a long string which is combination of words. Each word's first character is in uppercase and rest characters are in lowercase(CamelCase notation). Your task is to display those words along with total number of words.

Input

A single line of string.

helloWelcomeToJavaInterview

Output

print each words along with total number of words.

  • hello
  • Welcome
  • To
  • Java
  • Interview

A simple approach to solve this problem is to iterate over entire string character by character.and whenever any uppercase character is encountered then combine those character to a word and put them in a list. Here is the sample code for that.
import java.util.*;
public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.next();         String word="";         List<String> wordList = new ArrayList<String>();  
        for(int i=0; i<s.length(); i++){             while(i<s.length() && s.charAt(i) >= 'a' && s.charAt(i) <= 'z'){
                word += s.charAt(i);                 i++;             }             wordList.add(word);             word = "";             if(i<s.length()){                 word += s.charAt(i);             }         }         for(String w : wordList){             System.out.println(w);         }         System.out.println(wordList.size());     } }
Another good approach to solve this problem is using regular expression. The advantage of using regular expression is that we don't need to iterate the string character by character. But we can't use uppercase character as separator because if we do so then resulted word doesn't have first character (we get hello, elcome, o, ava etc.). So, here is the regular expression (?<!^)(?=[A-Z]). The two parts of the regex (?<!...) and (?=...) are zero-width assertions. The first one makes sure ^ (start of string) does not occur right before the match position and the second one ensures that [A-Z] (single capital letter) appears right after the match position. The actual match is empty because neither of the assertions actually match any characters. The entire expression merely matches a position.
import java.util.*;
    
public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.next();
        String[] output = s.split("(?<!^)(?=[A-Z])");
        System.out.println(output.length);
    }
}

 

No comments:

Post a Comment