How to use LINQ to separate a list element and inserting the results back to list

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

1 Answers

Anonymous User
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

var addMyspace = new List<string>{'!', '...', '\'', '.', ','};
 
foreach(var s in addMyspace)
{
     sentence = sentence.Replace(s, string.Format(' {0}',s));
}
//split

Answer