[英]How do I ignore every input after the first few characters in the console in C#?
[英]Searching the first few characters of every word within a string in C#
我是编程语言的新手。 我有一个要求,我必须根据搜索字符串返回记录。
例如,取以下三个记录和一个搜索字符串“Cal”:
加州大学
帕斯卡研究所
加州大学
我已经尝试过String.Contains
,但这三个都被返回了。 如果我使用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”匹配任何单词边界(标点符号,空格等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.