Skip to main content

Java String Token

Problem Statement
Given a string, find number of words in that string. For this problem a word is defined by a string of one or more english alphabets.
There are multiple ways to tokenize a string in java, learn how to tokenize a string in java and demonstrate your skill by solving this problem!
Input Format
A string not more than 400000 characters long. The string can be defined by following regular expression:
[A-Za-z !,?.\_'@]+
That means the string will only contain english alphabets, blank spaces and this characters: "!,?._'@".
Output Format
In the first line, print number of words
 n in the string. The words don't need to be unique. In the next n lines, print all the words you found in the order they appeared in the input.
Sample Input
He is a very very good boy, isn't he?
Sample Output
10
He
is
a
very
very
good
boy
isn
t
he

    import java.io.*;
    import java.util.*;

    public class Solution {

        static String[] retStringList(String inStr){
            String strOut=inStr.replace("!"," ")
                          .replace(","," ")
                          .replace("?"," ")
                          .replace("."," ")
                          .replace("_"," ")
                          .replace("'"," ")
                          .replace("@"," ");
            return strOut.split(" ");
        }
      
        public static void main(String[] args) 
        {

      
          Scanner scan = new Scanner(System.in);
          String s=scan.nextLine();
        //Complete the code
          String[] sOut=retStringList(s);
           int count=0;
            for(String strV:sOut){
              if(!strV.trim().equals("")){
                  count++;    
              }
              }
          System.out.println(count);
          for(String strV:sOut){
              if(!strV.trim().equals("")){
                  System.out.println(strV);    
              }
              }

        }
    }



Testcase 0
Input (stdin)
He is a very very good boy, isn't he?
Your Output (stdout)
10
He
is
a
very
very
good
boy
isn
t
he
Expected Output
10
He
is
a
very
very
good
boy
isn
t
he



Testcase1
Input (stdin)
Hello, thanks for attempting this problem! Hope it will help you to learn java! Good luck and have a nice day!
Your Output (stdout)
21
Hello
thanks
for
attempting
this
problem
Hope
it
will
help
you
to
learn
java
Good
luck
and
have
a
nice
day
Expected Output
21
Hello
thanks
for
attempting
this
problem
Hope
it
will
help
you
to
learn
java
Good
luck
and
have
a
nice
day




Comments