2011-02-11 130 views
12

我在單個字符串中有一個段落,我想獲得該段落中的所有單詞。如何獲得在c#中的字符串的所有單詞?

我的問題是,我不希望以(',','',''','',';',':','!等標點符號結尾的後綴單詞。 ',‘?’)和/ N/T等

我也不想用的話年代和「M如world's它應該只返回世界。

在這個例子中 he said. "My dog's bone, toy, are missing!"

該清單應該是:he said my dog bone toy are missing

+3

你爲什麼要忽略狗`s`中的's`? – Justin 2011-02-11 15:07:37

+2

難道你不能在白色字符上分割字符串,如空格,換行符和其他字符嗎?兩個空白之間的所有內容都是一個字... – Cipi 2011-02-11 15:09:53

回答

20

擴展在Shan's answer,我會考慮這樣的事情作爲一個起點:

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]

一個限制是,它不會處理縮寫井;例如「Y.M.C.A.」將被視爲四個字。我認爲這也可以通過將.作爲一個字符匹配在一個單詞中處理,然後剝離出來,如果它之後是一個句號(即,通過檢查它是只有句號以及最後一個字符)。

0

在空白處分割,修剪任何不是生成字符串中的字母的東西。

2

希望這是對你有幫助:

 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); 
-1

這裏有一個循環替換方法......不是很快,但解決這個問題的方式......

string result = "string to cut ' stuff. ! out of";

".',[email protected]".ToCharArray().ToList().ForEach(a => result = result.Replace(a.ToString(),""));

這是假定你想將它放回原來的字符串,而不是新的字符串或列表。

相關問題