Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string on multiple spaces in java [duplicate]

Tags:

java

string

split

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.

like image 344
Sachin Mhetre Avatar asked Oct 26 '12 05:10

Sachin Mhetre


People also ask

How do you trim double spacing in Java?

trim(). replaceAll(" +", " ") (with two spaces) is faster than . trim().

What does split \\ s+ do in Java?

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.

How do I split a string into multiple 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.

How do you replace multiple spaces in Java?

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.


1 Answers

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.

like image 85
Bhesh Gurung Avatar answered Sep 24 '22 09:09

Bhesh Gurung