Win a copy of Modern frontends with htmx this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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~
 
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Create a string tokenizer where you specify the deliminator (the constructor that takes 2 parameters).
 
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
try

String s = "aaa bbb ccc\\nddd eee fff";
 
Elouise Kivineva
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic