Jobert Enamno
Jobert Enamno

Reputation: 4461

C# Split by String[] Delimiter Match Exact Word Only

I have string where its value should be splitted by string delimiter. For example my delimiter is "at", I want to split only the string value by exact "at" keyword. Below is my sample string value

 var sampleStr= "at Metadata at quota at what at batter";

If I use the code below, the words with "at" in them are also splitted.

var result= sampleStr.Split(new string[] { "at" }, StringSplitOptions.None);

The result that I want is an array that if combined will be "Metadata quota what batter".

Please help.

Upvotes: 4

Views: 2800

Answers (4)

musefan
musefan

Reputation: 48415

You should make use of the surrounding whitespace....

First of all, wrap your original text in some whitespace to cope with "at" at the start and/or end:

sampleStr = " " + sampleStr + " ";

Then do you split like so:

var result = sampleStr.Split(new string[] { " at " }, StringSplitOptions.RemoveEmptyEntries);

Then you have the result you want.

Upvotes: 0

Tomas Grosup
Tomas Grosup

Reputation: 6514

 splitted = Regex.Split(text,@"\bat\s*\b"); 

\b denotes any word-boundary. \s* will match the whitespace characters after "at".

splitted : string [] = [|""; "Metadata "; "quota "; "what "; "batter"|]

If you don't need a Empty Space then try like below...

List<string> splitted = Regex.Split(phrase, @"\bat\s*\b",StringSplitOptions.RemoveEmptyEntries);

splitted : string [] = [| "Metadata "; "quota "; "what "; "batter"|]

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460108

Perhaps:

IEnumerable<string> wordsWithoutAt = sampleStr.Split()
    .Where(w => !StringComparer.OrdinalIgnoreCase.Equals(w, "at"));
string result = string.Join(" " , wordsWithoutAt);

Demo

If the case matters replace the StringComparer.OrdinalIgnoreCase part with != "at".

Upvotes: 3

Tigran
Tigran

Reputation: 62246

There is no any reliable solution on this, as this is very language and your string possible structure specific.

To make it easier you may think of splitting by " at " (at with spaces in front and back), but this will not reolve all possible problems by the way.

Example:

"I was loooking at the tree", will fail, as "at" here is not delimeter but a word inside a real phrase.

Upvotes: 0

Related Questions