2015-05-05 48 views
0

我有一些字符串這樣的2串: STR1 = STA001,STR2 = STA002,STR3 = STA003 並有代碼比較字符串:如何比較在C#

private bool IsSubstring(string strChild, string strParent) 
    { 
      if (!strParent.Contains(strChild)) 
      { 
       return false; 
      } 
      else return true; 
    } 

如果我有strChild = STA001STA002和strParent = STA001STA002STA003然後返回true,但是當我輸入strChild = STA001STA003並與strParent = STA001STA002STA003一起檢查時,儘管STA001STA003包含在strParent中,但返回false。我該如何解決它?

+5

「STA001STA003」不是「STA001STA002STA003」的子字符串 – Adrian

+0

我想要STA001STA003是STA001STA002STA003的子字符串。我怎樣才能做到這一點? –

+1

它聽起來像'STANNN'的東西應該是(個人)項目在列表中。 「STA001STA003」的兩個*部分*都出現在兩個字符串中,但不是整個字符串 – Plutonix

回答

0

Contains方法只查找完全匹配,它不查找字符串的部分。

劃分子串入的部分,並查找父字符串中的每個部分:

private bool IsSubstring(string child, string parent) { 
    for (int i = 0; i < child.Length; i+= 6) { 
    if (!parent.Contains(child.Substring(i, 6))) { 
     return false; 
    } 
    } 
    return true; 
} 

你應該考慮然而它的交叉部分匹配是可能的,如果這是一個問題。例如。在"STA001STA002"中尋找"1STA00"。如果這會是一個問題,那麼您應該類似地劃分父字符串,並且僅在各部分之間進行直接比較,而不使用方法Contains

注意:在C#中不鼓勵使用匈牙利符號表示變量的數據類型。

+0

如果我輸入strChild = STASTA,則與strParent = STA001STA002STA003比較 - >您的方式不正確。請幫助我! –

4

你所描述的不是子串。基本上要求兩個收藏的問題「是另一個的這個a subset?」當收集是a set(例如HashSet<T>)時,這個問題比集合是一個大連接字符串時要容易得多。

這是寫你的代碼一個更好的方法:

var setOne = new HashSet<string> { "STA001", "STA003" }; 

var setTwo = new HashSet<string> { "STA001", "STA002", "STA003" }; 

Console.WriteLine(setOne.IsSubsetOf(setTwo)); // True 
Console.WriteLine(setTwo.IsSubsetOf(setOne)); // False 

或者,如果STA00部分只是填充物,使其意義的字符串的情況下,然後使用int小號直接:

var setOne = new HashSet<int> { 1, 3 }; 

var setTwo = new HashSet<int> { 1, 2, 3 }; 

Console.WriteLine(setOne.IsSubsetOf(setTwo)); // True 
Console.WriteLine(setTwo.IsSubsetOf(setOne)); // False 
0

這可能在矯枉過正的一面,但它可能是非常有益的。

private static bool ContainedWord(string input, string phrase) 
{ 
    var pattern = String.Format(@"\b({0})", phrase); 
    var result = Regex.Match(input, pattern); 

    if(string.Compare(result, phrase) == 0) 
      return true; 

    return false; 
} 

如果表達式找到匹配項,則將結果與您的詞組進行比較。如果它們爲零,則匹配。我可能會誤解你的意圖。