2

我是编程语言的新手。我有一个要求,我必须根据搜索字符串返回记录。

例如,取以下三个记录和一个搜索字符串“Cal”:

  1. 加州大学

  2. 帕斯卡学院

  3. 加州大学

我试过String.Contains了,但是三个都被退回了。如果我使用String.StartsWith,我只会得到记录#3。我的要求是在结果中返回#1 和#3。

谢谢您的帮助。

4

7 回答 7

4

如果您使用的是 .NET 3.5 或更高版本,我建议您使用LINQ 扩展方法。签出String.SplitEnumerable.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;
    }
}
于 2012-09-27T21:37:26.650 回答
2

为了简单起见,我喜欢这个:

if(str.StartsWith("Cal") || str.Contains(" Cal")){
    //do something
}
于 2012-09-27T21:45:59.470 回答
2

你可以试试:

foreach(var str in stringInQuestion.Split(' '))
{
  if(str.StartsWith("Cal"))
   {
      //do something
   }
}
于 2012-09-27T21:36:30.613 回答
0

您可以使用正则表达式来查找匹配项。这是一个例子

    //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");
    }
于 2012-09-27T21:46:28.260 回答
0
        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();
    }
于 2012-09-27T23:05:41.327 回答
0
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
于 2012-09-27T23:12:24.910 回答
0

这实际上是正则表达式的一个很好的用例。

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" 匹配任何单词边界(标点符号、空格等)。

于 2012-09-27T23:15:03.593 回答