私はプログラミング言語に不慣れです。検索文字列に基づいてレコードを返す必要があるという要件があります。
たとえば、次の3つのレコードと「Cal」の検索文字列を考えます。
カリフォルニア大学
パスカルインスティテュート
カリフォルニア大学
試しましString.Contains
たが、3つすべてが返されます。を使用するString.StartsWith
と、レコード#3しか取得できません。私の要件は、結果に#1と#3を返すことです。
ご協力ありがとうございました。
私はプログラミング言語に不慣れです。検索文字列に基づいてレコードを返す必要があるという要件があります。
たとえば、次の3つのレコードと「Cal」の検索文字列を考えます。
カリフォルニア大学
パスカルインスティテュート
カリフォルニア大学
試しましString.Contains
たが、3つすべてが返されます。を使用するString.StartsWith
と、レコード#3しか取得できません。私の要件は、結果に#1と#3を返すことです。
ご協力ありがとうございました。
.NET 3.5以降を使用している場合は、LINQ 拡張メソッドを使用することをお勧めします。チェックアウトしString.Split
てEnumerable.Any
。何かのようなもの:
string myString = "University of California";
bool included = myString.Split(' ').Any(w => w.StartsWith("Cal"));
Split
スペース文字で分割myString
し、文字列の配列を返します。Any
配列で機能し、文字列のいずれかが。で始まる場合はtrueを返します"Cal"
。
使用したくない、または使用できない場合Any
は、単語を手動でループする必要があります。
string myString = "University of California";
bool included = false;
foreach (string word in myString.Split(' '))
{
if (word.StartsWith("Cal"))
{
included = true;
break;
}
}
あなたが試すことができます:
foreach(var str in stringInQuestion.Split(' '))
{
if(str.StartsWith("Cal"))
{
//do something
}
}
私は簡単にするためにこれが好きです:
if(str.StartsWith("Cal") || str.Contains(" Cal")){
//do something
}
正規表現を使用して一致を見つけることができます。これが例です
//array of strings to check
String[] strs = {"University of California", "Pascal Institute", "California University"};
//create the regular expression to look for
Regex regex = new Regex(@"Cal\w*");
//create a list to hold the matches
List<String> myMatches = new List<String>();
//loop through the strings
foreach (String s in strs)
{ //check for a match
if (regex.Match(s).Success)
{ //add to the list
myMatches.Add(s);
}
}
//loop through the list and present the matches one at a time in a message box
foreach (String matchItem in myMatches)
{
MessageBox.Show(matchItem + " was a match");
}
string univOfCal = "University of California";
string pascalInst = "Pascal Institute";
string calUniv = "California University";
string[] arrayofStrings = new string[]
{
univOfCal, pascalInst, calUniv
};
string wordToMatch = "Cal";
foreach (string i in arrayofStrings)
{
if (i.Contains(wordToMatch)){
Console.Write(i + "\n");
}
}
Console.ReadLine();
}
var strings = new List<string> { "University of California", "Pascal Institute", "California University" };
var matches = strings.Where(s => s.Split(' ').Any(x => x.StartsWith("Cal")));
foreach (var match in matches)
{
Console.WriteLine(match);
}
出力:
University of California
California University
これは実際には正規表現の良いユースケースです。
string[] words =
{
"University of California",
"Pascal Institute",
"California University"
}
var expr = @"\bcal";
var opts = RegexOptions.IgnoreCase;
var matches = words.Where(x =>
Regex.IsMatch(x, expr, opts)).ToArray();
「\b」は任意の単語境界(句読点、スペースなど)に一致します。