简体   繁体   English

在C#中搜索字符串中每个单词的前几个字符

[英]Searching the first few characters of every word within a string in C#

I am new to programming languages. 我是编程语言的新手。 I have a requirement where I have to return a record based on a search string. 我有一个要求,我必须根据搜索字符串返回记录。

For example, take the following three records and a search string of "Cal": 例如,取以下三个记录和一个搜索字符串“Cal”:

  1. University of California 加州大学

  2. Pascal Institute 帕斯卡研究所

  3. California University 加州大学

I've tried String.Contains , but all three are returned. 我已经尝试过String.Contains ,但这三个都被返回了。 If I use String.StartsWith , I get only record #3. 如果我使用String.StartsWith ,我只获得记录#3。 My requirement is to return #1 and #3 in the result. 我的要求是在结果中返回#1和#3。

Thank you for your help. 谢谢您的帮助。

If you're using .NET 3.5 or higher, I'd recommend using the LINQ extension methods . 如果您使用的是.NET 3.5或更高版本,我建议使用LINQ 扩展方法 Check out String.Split and Enumerable.Any . 查看String.SplitEnumerable.Any Something like: 就像是:

string myString = "University of California";
bool included = myString.Split(' ').Any(w => w.StartsWith("Cal"));

Split divides myString at the space characters and returns an array of strings. SplitmyString除以空格字符并返回一个字符串数组。 Any works on the array, returning true if any of the strings starts with "Cal" . Any阵列上的作品,返回true,如果任何字符串的开头"Cal"

If you don't want to or can't use Any , then you'll have to manually loop through the words. 如果您不想或不能使用Any ,那么您将不得不手动循环使用单词。

string myString = "University of California";
bool included = false;

foreach (string word in myString.Split(' '))
{
    if (word.StartsWith("Cal"))
    {
        included = true;
        break;
    }
}

You can try: 你可以试试:

foreach(var str in stringInQuestion.Split(' '))
{
  if(str.StartsWith("Cal"))
   {
      //do something
   }
}

I like this for simplicity: 我这样简单:

if(str.StartsWith("Cal") || str.Contains(" Cal")){
    //do something
}

You can use Regular expressions to find the matches. 您可以使用正则表达式来查找匹配项。 Here is an example 这是一个例子

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

Output: 输出:

University of California
California University

This is actually a good use case for regular expressions. 这实际上是正则表达式的一个很好的用例。

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

The "\\b" matches any word boundary (punctuation, space, etc...). “\\ b”匹配任何单词边界(标点符号,空格等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM