Possible Duplicate:
How to split a String by space
I need help while parsing a text file. The text file contains data like
This is different type of file. Can not split it using ' '(white space)
My problem is spaces between words are not similar. Sometimes there is single space and sometimes multiple spaces are given.
I need to split the string in such a way that I will get only words, not spaces.
trim(). replaceAll(" +", " ") (with two spaces) is faster than . trim().
split("\\s+") will split the string into string of array with separator as space or multiple spaces. \s+ is a regular expression for one or more spaces.
To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.
To replace the multiple white spaces from a string with a single white space, we can use the replaceAll() method by passing the //s+ regex as a first argument and single space ( " " ) as the second argument.
str.split("\\s+")
would work. The +
at the end of the regular-expression, would treat multiple spaces the same as a single space. It returns an array of strings (String[]
) without any " "
results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With