【发布时间】:2014-08-15 14:27:54
【问题描述】:
我有一个这样的字符串列表(""Joe", "wants", "to", "谢谢", "you!"") 我想要的是分开 "you", "!"和 """ 并使用 LINQ 将它们插入回该列表。我知道这里有很多 LINQ 专家,可以在一分钟内完成。我正在做的是将一个句子分成单词:
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("\"");
}
}
问题在于句子以 !" 结尾。注意:words 是由空格分隔的数组。
【问题讨论】:
-
这些字符串有什么模式吗?似乎定期删除可以完成工作。
-
@liran63 ??如何将一个单独的单词删除后跟一个标点符号,将其放回列表中?
-
在您的代码中,
(""", "Joe", "wants", "to", "thank", "you!", """)是否只是"Joe wants to thank you!"? -
我猜他正在寻找的只是添加另一个 else if (word.EndsWith("!")) ... ;还是我错过了什么?
-
你可以先
string.replace("!", " !"),然后再用空格分割