Reputation: 33
I am new to C# and only know the basics. I'm looking for a code example on how I would get every other word from a string variable. For example if the variable was
String x = "Help me, coding is difficult";
I would want to return single string "Help coding difficult". It needs to be a function that takes one string and return filtered version of it.
Someone suggested duplicates that I mostly already seen during my research:
Upvotes: 2
Views: 787
Reputation: 460098
You need to define first what are word delimiters, just a space, a comma, period or semicolon or what else? Then you can use String.Split
.
char[] wordDelimiter = new[] { ' ','\t', ',', '.', '!', '?', ';', ':', '/', '\\', '[', ']', '(', ')', '<', '>', '@', '"', '\'' };
String x = "Help me, coding is difficult";
string[] words = x.Split(wordDelimiter, StringSplitOptions.RemoveEmptyEntries);
Now you have an array with all words. But you want every other, you could fill them into a List<string>
and use a for-loop
that skips every other:
var everyOtherWord = new List<string>();
for(int i = 0; i < words.Length; i += 2)
{
everyOtherWord.Add(words[i]);
}
I would want to return "Help coding difficult"
So you really want to have a string
as result that contains these words separated by space? Then use String.Join
(somehow the counterpart method of String.Split
):
string result = string.Join(" ", everyOtherWord);
Upvotes: 4
Reputation: 17520
Assuming that you count a word as "every character between spaces, or the start/end of the string", and you're not trying to remove any letters.
var input = "Help me, coding is difficult";
var everyOther = input
.Split(' ')
.Where((x, i) => i % 2 == 0);
Console.WriteLine(string.Join(" ", everyOther));
The code for the Where
was taken from this post.
The idea is to use the overload of Where
which gives you the index value, and see if that index value is even, if so, include it in the results.
Upvotes: 1
Reputation: 1241
string s = "You win some. You lose some.";
string[] subs = s.Split(' ');
for(int i=0 ; i < subs.length ; i+=2)
{
Console.WriteLine($"Substring: {sub[i]}");
}
Upvotes: 0