[英]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.