0

This is the input

hello; this is cool?
great,   awesome

I want my output to be

hello;
this
is
cool?
great,
awesome

I basically consider a word to have punctuation in it. That's my definition of word for my application. I want to split words based on space, tabspace and newline. Most of the stackoverflow questions and answers assume that word doesn't include punctuation so how would I solve this?

posixKing
  • 408
  • 1
  • 8
  • 17

1 Answers1

-1

Comments ans explanations directly in the code:

//1st possibility: every single whitespace character (space, tab, newline, carriage return, vertical tab) will be treated as a separator
String s="hello; this is cool?\ngreat,   awesome";
String[] array1 = s.split("\\s");
System.out.println("======first case=====");
for(int i=0; i<array1.length; i++)
    System.out.println(array1[i]);

//2nd possibility (groups of consecutive whitespace characters (space, tab, newline, carriage return, vertical tab) will be treated as a single separator
String[] array2 = s.split("\\s+");
System.out.println("=====second case=====");
for(int i=0; i<array2.length; i++)
    System.out.println(array2[i]);
//notice the difference in the output!!!

output:

======first case=====
hello;
this
is
cool?
great,
         <----- Notice the empty string
         <----- Notice the empty string
awesome
=====second case=====
hello;
this
is
cool?
great,
awesome
Allan
  • 12,117
  • 3
  • 27
  • 51
  • could you please let a comment if you downvote? In order for us to get a feedback! Thank you – Allan Feb 11 '18 at 01:43