Joshua
Joshua

Reputation: 2295

strip of words from a string in .net

I need to keep the first 5 words from returned string, stripping of the balance.

eg. I want to keep "Stackoverflow is an amazing resources" from the word below

Stackoverflow is an amazing resources for developers

Upvotes: 1

Views: 1568

Answers (3)

paulius_l
paulius_l

Reputation: 4993

Ok, a little fancier solution:

int remainingWords = 5;
System.Text.RegularExpressions.Regex.Replace("Stackoverflow is an amazing resources for developers", "(.+? )|(.+?)", match =>
        {
        return remainingWords-- > 0 ? match.Value : "";
        });

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460138

You could use Substring in combination with IndexOf.

Dim amazing = "Stackoverflow is amazing"
Dim notAmazing = amazing.Substring(0,  amazing.IndexOf(" is amazing"))

Or you could use Remove:

Dim notAmazing = amazing.Remove(amazing.IndexOf(" is amazing"))

Or (as answered by paulius_i) Replace:

Dim notAmazing = amazing.Replace(" is amazing", String.Empty)

Edit: You've modified your question essentially, so here is a way to get the first n words of a string:

Dim amazing = "Stackoverflow is an amazing resources for developers"
Dim words = amazing.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
Dim first5Words = String.Join(" ", words.Take(5))

Upvotes: 1

ChrisF
ChrisF

Reputation: 137148

Firstly split the string into words:

var words = inputString.Split(' ', StringSplitOptions.RemoveEmptyEntries)

Though you may need to use an overload to cater for other whitespace characters.

Next take the first 5 words:

var firstFive = words.Take(5)

This will return up to the first five words so it won't matter if there are less than 5 in the input string.

Finally recreate a sentence:

var output = string.Join(" ", firstFive)

Obviously you can combine these steps.

Upvotes: 2

Related Questions