user3403621
user3403621

Reputation: 77

How to split string to words?

So I have some irregular string that I would like to split into words. String can contain multiple spaces and line breaks consecutively. I.e. String:

"Word1     
Word2

Word3 Word4        Word5" 

Would turn out as:

"Word1 Word2 Word3 Word4 Word5"

Words can contain special characters, but not spaces or linebreaks.

Upvotes: 1

Views: 106

Answers (5)

Paolo Fulgoni
Paolo Fulgoni

Reputation: 5498

This could make sense if you have Guava as dependency:

String yourString = "Word1 \n" + "Word2 \n"
        + "Word3 Word4               Word5";

String result = Joiner.on(" ").join(
        Splitter.onPattern("\\s+").split(yourString));

System.out.println(result);

See explanation of Splitter/Joiner here

Upvotes: 0

Dexters
Dexters

Reputation: 2495

public class HelloWorld{

     public static void main(String []args){
         String sentence = "Word1 Word2 Word3 Word4 Word5";
        System.out.println(sentence.replace("\\s"," "));
     }
}

\\s same as [ \\t\\n\\x0B\\f\\r]

Output:

Word1 Word2 Word3 Word4 Word5

Upvotes: 0

Bette Devine
Bette Devine

Reputation: 1194

String yourString = "your string      " +
                "word2       " +
                "word3";

String test = yourString.trim().replaceAll("\\s+", " ");
String[] array = test.split(" |\r");

Upvotes: 0

Mena
Mena

Reputation: 48404

If you need to replace all whitespace (including line breaks) with one space character, you can use the following;

String input = "word0\r\nword1 word2";
//                       | replace all instances of...
//                       |           | ... one or more whitespace (including line breaks)
//                       |           |       ... with a single space 
System.out.println(input.replaceAll("\\s+", " "));

Output

word0 word1 word2

Upvotes: 2

Shriram
Shriram

Reputation: 4411

Use String.split() api or java.util.strintokenizer.

Upvotes: 0

Related Questions