aspose file tools*
The moose likes Beginning Java and the fly likes How to split a string by the whitespace but ignoring '\n'? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to split a string by the whitespace but ignoring Watch "How to split a string by the whitespace but ignoring New topic
Author

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

Howard Ting
Greenhorn

Joined: Feb 17, 2004
Posts: 19
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

Joined: Feb 07, 2002
Posts: 154
Create a string tokenizer where you specify the deliminator (the constructor that takes 2 parameters).
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
try

String s = "aaa bbb ccc\\nddd eee fff";
Elouise Kivineva
Ranch Hand

Joined: Feb 07, 2002
Posts: 154
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

Joined: Jun 09, 2003
Posts: 4632
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to split a string by the whitespace but ignoring '\n'?