2012-03-22 106 views
2

環境:微軟的Visual Studio 2008的C#的indexOf exactvalue比賽

如何獲得字符串中發現整個詞的索引

string dateStringsToValidate = "birthdatecake||birthdate||other||strings"; 
string testValue = "birthdate"; 

var result = dateStringsToValidate.IndexOf(testValue); 

它並不一定是我做這件事的方式例如,使用正則表達式還是其他方法會更好?

更新: 這個詞是birthdate not birthdatecake。它不必檢索匹配,但索引應該找到正確的詞。我不認爲IndexOf是我正在尋找的東西。抱歉不清楚。

+0

咦? – SLaks 2012-03-22 19:59:52

+3

他意味着像'全字'匹配。 – payo 2012-03-22 20:02:25

+0

您的確切測試用例最簡單的解決方案是將您的testValue更改爲「birthdate |」,但我認爲您需要一個更靈活的解決方案。你需要更確切地定義你的問題。 – 2012-03-22 20:16:21

回答

8

使用此

string dateStringsToValidate = "birthdatecake||birthdate||other||strings"; 
    string testValue = "strings"; 
    var result = WholeWordIndexOf(dateStringsToValidate, testValue); 

// ... 

public int WholeWordIndexOf(string source, string word, bool ignoreCase = false) 
{ 
    string testValue = "\\W?(" + word + ")\\W?"; 

    var regex = new Regex(testValue, ignoreCase ? 
     RegexOptions.IgnoreCase : 
     RegexOptions.None); 

    var match = regex.Match(source); 
    return match.Captures.Count == 0 ? -1 : match.Groups[0].Index; 
} 

正則表達式瞭解更多關於在C#中的正則表達式選項here

另一種選擇,根據您的需要,是分割字符串(因爲我看到你有一定的分隔符) 。請注意,此選項返回的索引是按字數統計的索引,而不是字符數(在此情況下爲1,因爲C#具有基於零的陣列)。

string dateStringsToValidate = "birthdatecake||birthdate||other||strings"; 
    var split = dateStringsToValidate.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries); 
    string testValue = "birthdate"; 
    var result = split.ToList().IndexOf(testValue); 
+0

因爲我認爲他想要整個單詞 – payo 2012-03-22 20:02:42

+2

第二種方法將返回分割列表中字符串匹配的索引,而不是源字符串。 – 2012-03-22 20:13:11

+0

@AdrianIftode我在第二個選項中添加了一些上下文來說明這一點。謝謝。 – payo 2012-03-22 20:14:36

0

如果必須處理給定的字符串中的精確索引,那麼這是沒有多大用處的給你。如果你只是想在字符串中找到最佳匹配,這可能適合你。

var dateStringsToValidate = "birthdatecake||birthdate||other||strings"; 
var toFind = "birthdate"; 

var splitDateStrings = dateStringsToValidate.Split(new[] {"||"}, StringSplitOptions.None); 
var best = splitDateStrings 
    .Where(s => s.Contains(toFind)) 
    .OrderBy(s => s.Length*1.0/toFind.Length) // a metric to define "best match" 
    .FirstOrDefault(); 

Console.WriteLine(best);