[英]How do I pick a specific word out of a string with certain criteria?
我希望能夠找到以大寫字母開頭的特定長度(3 - 99 個字符)的單詞。 例如,在下面的句子中(實際句子將由用戶相應地編寫和填寫)
My name is John and i am 20 years old.
我希望選擇“約翰”這個詞,因為它符合所有標准。
到目前為止,這是我的代碼:(我知道這很混亂,抱歉我對此比較陌生)
static void Main(string[] args)
{
Console.Write("Name and age: ");
string a = Console.ReadLine();
string b = string.Empty;
int val;
for (int i = 0; i < a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length > 0)
val = int.Parse(b);
string inputStr = a;
string outputStr = String.Concat(inputStr.Where(x => Char.IsUpper(x)));
Console.WriteLine("Your name is " + outputStr);
Console.WriteLine("You are " + b + " years old");
Console.ReadLine();
}
我試圖讓程序告訴我:
Your name is John
You are 20 years old
我讓程序告訴我年齡,但到目前為止,我只能讓它給我大寫字母(字符串中的任何地方)
您可以先將句子分成單詞,然后 select 以大寫字母開頭的單詞(前提是它們用空格分隔)
int minLength = 3;
int maxLength = 99;
string[] CapWords = inputStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Where(x => char.IsUpper(x[0])&& x.Length>= minLength && x.Length <= maxLength)
.ToArray<string>();
string outputStr = CapWords[1];
實際上,只有當您的句子中的第一個單詞以大寫字母開頭但不是名稱時,它才有效,然后以大寫字母開頭的第二個單詞是您要查找的名稱。
這對於您想要做的事情可能有點過分,但通常正則表達式(正則表達式)是解析字符串的好方法:
using System.Text.RegularExpressions;
string pattern = @"(?!^)\b[A-Z][a-z]{2,98}\b";
string input = "My name is John and i am 20 years old.";
string output = Regex.Match(input, pattern).Value;
Regexr是創建這些的絕佳工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.