user1381656
user1381656

Reputation:

How to split a string with more than one whitespaces as delimiters?

I have strings where one whitespace must not be a delimiter. But when more than one whitespaces occur consecetively, it must act as delimiter. e.g.

"Line 1     Component Name             Revision        Quantity   Unit"

Here in this example I must have 5 different elements after split. How can I implement it with built-in split function in string. (please note that single occurence of whitespace do not act as delimiter)

Upvotes: 5

Views: 8074

Answers (4)

Jatin Malwal
Jatin Malwal

Reputation: 5263

Here u r...

String fields = "He rl  lo vjdvd    fcsd";

Pattern pattern = Pattern.compile("\\s\\s\\s*" );

String[] split = pattern.split(fields);
for (String string : split) {
    //Use values here
}

Upvotes: 0

Jordy Langen
Jordy Langen

Reputation: 3591

Hmm, not sure if this will cover all your cases:

var regex = new Regex("  +");
var result = regex.Split("Line 1     Component Name             Revision        Quantity   Unit");

Result:

Line 1
Component Name
Revision
Quantity
Unit

Upvotes: 3

Guillaume Lafrance
Guillaume Lafrance

Reputation: 67

Well, you could always use :

String newStr = str.Split("<White space><White space>");

Upvotes: 0

Chris Sinclair
Chris Sinclair

Reputation: 23208

Split on two spaces, then trim any excess you might get in your results (would occur if you have an odd number of spaces)

List<string> splitStrings = myString.Split(new[]{"  "}, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => s.Trim())
    .ToList();

Upvotes: 9

Related Questions