[英]How to get all words of a string in c#?
我在一個字符串中有一個段落,我想得到該段落中的所有單詞。
我的問題是我不希望后綴的單詞以標點符號結尾,例如(',','。',''',''',';',':','!','? ')和/ n / t等
我也不想要像world's
那樣只有回歸世界的話語。
在he said. "My dog's bone, toy, are missing!"
的例子中he said. "My dog's bone, toy, are missing!"
he said. "My dog's bone, toy, are missing!"
名單應該是: he said my dog bone toy are missing
根據Shan的回答 ,我會考慮這樣的出發點:
MatchCollection matches = Regex.Match(input, @"\b[\w']*\b");
為什么包括'
角色? 因為這會阻止像“我們”這樣的單詞被分成兩個單詞。 捕獲后,您可以自己手動刪除后綴(否則,您無法識別re
不是單詞而忽略它)。
所以:
static string[] GetWords(string input)
{
MatchCollection matches = Regex.Matches(input, @"\b[\w']*\b");
var words = from m in matches.Cast<Match>()
where !string.IsNullOrEmpty(m.Value)
select TrimSuffix(m.Value);
return words.ToArray();
}
static string TrimSuffix(string word)
{
int apostropheLocation = word.IndexOf('\'');
if (apostropheLocation != -1)
{
word = word.Substring(0, apostropheLocation);
}
return word;
}
輸入示例:
he said. "My dog's bone, toy, are missing!" What're you doing tonight, by the way?
示例輸出:
[he, said, My, dog, bone, toy, are, missing, What, you, doing, tonight, by, the, way]
這種方法的一個限制是它不能很好地處理首字母縮略詞; 例如,“YMCA”將被視為四個單詞。 我認為也可以通過包括來處理.
作為一個字符在一個單詞中匹配,然后在它之后完全停止時將其剝離(即通過檢查它是單詞中的唯一句點以及最后一個字符)。
希望這對你有所幫助:
string[] separators = new string[] {",", ".", "!", "\'", " ", "\'s"};
string text = "My dog's bone, toy, are missing!";
foreach (string word in text.Split(separators, StringSplitOptions.RemoveEmptyEntries))
Console.WriteLine(word);
請參閱正則表達式單詞邊界表達式 , 計算richtextbox中所有單詞的最有效方法是什么? 。 故事的道德是有很多方法來解決問題,但正則表達式可能是簡單的方法。
在空格上拆分,修剪結果字符串上不是字母的任何內容。
這是一個循環替換方法......不是很快,但解決它的方法......
string result = "string to cut ' stuff. ! out of";
".',!@".ToCharArray().ToList().ForEach(a => result = result.Replace(a.ToString(),""));
這假設您要將其放回原始字符串中,而不是新字符串或列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.