2010-01-15 143 views
3

我想比較一個字符串和很多字符串。這是如何在C#中完成的?比較一個字符串和幾個不同的字符串

+2

OK,看完這個任務後,離子幾次,也deepasundaris自己的答案與額外的信息,我認爲他想要以下內容: 我有一個字符串的列表,需要找到一個未知的子字符串,該列表中的每個字符串中存在 – Oliver 2010-01-15 07:42:41

+0

請重新短語問題以反映你真正的意思。 – Yoni 2010-01-15 07:57:34

+0

您能否編輯您的初始問題以提供更多信息?我注意到你在這裏的一些評論中澄清了這個問題,但最好的方法是更新問題本身,這樣人們就不必通過所有的答案來了解你需要什麼。 – 2010-01-15 08:02:48

回答

8

如果你想檢查一個字符串包含在一個字符串列表,你可以使用Contains擴展方法:

bool isStringContainedInList = 
    new[] { "string1", "string2", "string3" }.Contains("some string") 
+0

但問題是我dono什麼是「一些字符串」我想找到... 如何做到這一點? 找到很多字符串之間的共同點... – user251334 2010-01-15 07:31:38

0
string[] comparisonList = {"a", "b" "c"}; 
from s in comparisonList where comparisonList.Contains("b") select s; 
+4

我不認爲LINQ在這裏真的有必要。 – 2010-01-15 07:16:54

+0

@musicfreak:meh。 @ash:自LINQ發佈以來已經有4年了。 – 2010-01-15 07:24:04

0

如果你想比較,使用String.Compare
如果您在列表中查找字符串,請使用與列表類型等效的Contains/Select方法。

0

我喜歡使用String.Compare()靜態方法,因爲它可以讓您將所有內容都顯式化。這一點很重要,因爲字符串比較可能因微妙的錯誤而臭名昭着。

例如:

// Populate with your strings 
List<string> manyStrings = new List<string>(); 

string oneString="target string"; 

foreach(string current in manyStrings) 
{ 
    // For a culture aware, safe comparison 
    int compareResult=String.Compare(current,oneString, 
         StringComparison.CurrentCulture); 
    // OR 
    // For a higher performance comparison 
    int compareResult=String.Compare(current,oneString, 
         StringComparison.Ordinal); 

    if (compareResult==0) 
    { 
     // Strings are equal 

    } 
} 

如果你真的只想知道一個字符串是否是另一個較大字符串的子,在上面的循環中,您可以使用:

int indexPos=current.IndexOf(oneString,StringComparison.Ordinal); 

if (indexPos>=0) 
{ 
    // oneString was found in current 
} 

注意的IndexOf接受相同的有用StringComparison枚舉。

0

要查找列表中的多個列表中的字符串,您可以開始將這些字符串放入HashSet中,然後檢查每個字符串是否已存在於此集合中。

例如,你可以:

HashSet<string> hashSet = new HashSet<string>(); 

foreach (string item in myList) 
{ 
    if (hashSet.Contains(item)) 
    { 
     // already in the list 
     ... 
    } 
    else 
    { 
     // not seen yet, putting it into the hash set 
     hashSet.Add(item); 
    } 
} 
6

我建議你看看這個維基百科article有關最長公共子串

我記得從本科生那裏找到最長的公共子字符串的策略,你可以先找到一個稍短的子字符串,然後從那裏(和重複)擴展。也就是說,如果「abcd」是一個常見的子字符串,那麼「abc」也是如此,「ab」也是如此。

這適用於重複算法,首先找到出現在字符串中的所有2個字母對(我不打擾使用一個字母子字符串,因爲對於大數據集,它們將包含整個字母表)。然後你再遍歷查找所有三字母串,等等...

4

到集合中的所有字符串比較彼此找到重複的,這是最有效的使用詞典:

string[] strings = { "Zaphod", "Trillian", "Zaphod", "Ford", "Arthur" }; 

var count = new Dictionary<string, int>(); 
foreach (string s in strings) { 
    if (count.ContainsKey(s)) { 
    count[s]++; 
    } else { 
    count.Add(s, 1); 
    } 
} 
foreach (var item in count) { 
    Console.WriteLine("{0} : {1}", item.Key, item.Value); 
} 

輸出:

Zaphod : 2 
Trillian : 1 
Ford : 1 
Arthur : 1 

您也可以使用LINQ方法做到這一點:

var count = 
    strings 
    .GroupBy(s => s) 
    .Select(
    g => new { Key = g.First(), Value = g.Count() } 
); 
+0

不錯的代碼,但它並沒有回答這個問題,我的意圖是 – Yoni 2010-01-15 08:44:36

+0

@Yoni:如果你知道OP的確切意圖,請將它發佈到這個問題的某個地方。 – Guffa 2010-01-15 11:19:05