• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to split a string by the whitespace but ignoring '\n'?

 
Howard Ting
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s = "aaa bbb ccc\nddd eee fff";
String ss = s.split("\\s");

My expected result is "aaa", "bbb", "ccc\nddd", "eee", "fff", the the real result is "aaa", "bbb", "ccc", "ddd", "eee", "fff".
How can I get my desired result?
Thanks in advance~
 
Elouise Kivineva
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create a string tokenizer where you specify the deliminator (the constructor that takes 2 parameters).
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try

String s = "aaa bbb ccc\\nddd eee fff";
 
Elouise Kivineva
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You ARE getting your expected result from tokenizing but it looks like you are printing your result to see what tokens you get and misunderstanding the result:
The token "ccc\nddd" is printing as ccc(NEWLINE)ddd and maybe you are mistaking it for 2 different tokens "ccc" and "ddd".

Try looking at the results from
StringTokenizer st = new StringTokenizer( s , " " , true );
and maybe you can see what I mean.

-------

What the method s.split("\\s") is, I don't know. s.split( s ) i could understand.
[ May 24, 2004: Message edited by: Elouise Kivineva ]
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s = "aaa bbb ccc\nddd eee fff";
String[] ss = s.split("[\\s&&[^\n]]");
for(int x = 0; x < ss.length;x++)System.out.println(ss[x]+" "+x);

output:

aaa 0
bbb 1
ccc
ddd 2
eee 3
fff 4
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic