java - How to split() a String while maintaining whitespace -


this question has answer here:

how split string of words , retain whitespaces?

here code:

string words[] = s.split(" ");  

string s contains: hello world

after code runs, words[] contains: "hello" "" world

ideally, should not empty string in middle, contain both whitespaces: words[] should be: "hello" " " " " world

how have result?

you use lookahead/lookbehind assertions:

string[] words = "hello  world".split("((?<=\\s+)|(?=\\s+))"); 

where (?<=\\s+) , (?=\\s+) zero-width groups.


Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -