I have a list of strings like this(""Joe", "wants", "to", "thank", "you!"") what I want is to separate "you", "!" and """ and insert them back to that list using LINQ. I know there are many LINQ experts here, which can do it in a minute. What I'm doing is separating a sentence into words:
string sentence = "\"Joe wants to thank you!\"";
string[] words = sentence.split(" ");
List<string> result = new List<string>();
for (int i = 0; i < words.Length; i++)
{
string word = words[i];
if (word.EndsWith("."))
{
result.Add(word.Substring(0, word.LastIndexOf(".")));
result.Add(".");
}
else if (word.EndsWith("..."))
{
result.Add(word.Substring(0, word.LastIndexOf("...")));
result.Add("...");
}
else if (word.EndsWith(","))
{
result.Add(word.Substring(0, word.LastIndexOf(",")));
result.Add(",");
}
else if (word.EndsWith("\""))
{
result.Add(word.Substring(0, word.LastIndexOf("\"")));
result.Add("\"");
}
}
The problem is with sentence that ends with !". NOTE: words is the array splitted by space.
Last updated:1/27/2015 12:14:06 AM
Anonymous User
since you are already splitting it by spaces, just replace and add a space before splitting up
sentence = sentence.Replace('!', ' !');
I don't think you need linq but something kind of elegant for you would be