2012-03-22 9 views
2

環境:マイクロソフトのVisual Studio 2008のC#IndexOfメソッドexactvalueマッチ

は、私は、文字列で見つかった単語全体のインデックスを取得するにはどうすればよい

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

var result = dateStringsToValidate.IndexOf(testValue); 

それは私がやった方法である必要はありません。たとえば、正規表現やその他の方法を使用する方がよいでしょうか?

更新: 単語は生年月日ではなく、生年月日です。それは一致を検索する必要はありませんが、インデックスは正しい単語を見つける必要があります。私はIndexOfが私が探しているものだとは思わない。不明な点がありましたら申し訳ありません。この

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; 
} 

ため

+0

Huh? – SLaks

+3

彼は「完全な単語」のような何かを意味します。 – payo

+0

正確なテストケースの最も簡単な解決策は、testValueを "birthdate |"に変更することですが、それよりも柔軟な解決策が必要だと思います。問題をもう少し正確に定義する必要があります。 –

答えて

8

使用正規表現は、C#での正規表現のオプション詳細については、こちらをご覧くださいhere

別のオプションは、あなたのニーズに応じて、(私はあなたには、いくつかの区切り文字を持って見るように)文字列を分割することです。このオプションによって返されるインデックスは、文字カウントではなく単語カウントによるインデックスであることに注意してください(この場合、C#には0から始まる配列があります)。

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

+2

2番目の方法は、ソース文字列ではなく分割リストの文字列一致のインデックスを返します。 –

+0

@AdrianIftodeそれを明確にするために2番目のオプションにいくつかのコンテキストを追加しました。ありがとうございました。 – payo

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