C# 如何从字符串提取符合条件(大写开头、长度3-99)的目标单词
代码修正方案
原逻辑的错误点
你目前写的人名提取代码String.Concat(inputStr.Where(x => Char.IsUpper(x)))存在本质偏差:它只会遍历所有字符、把碰到的大写字符单独拼接,既不会识别连续字符组成的完整单词,也不会校验「以大写开头、长度3-99」的规则。比如用示例输入运行的话,这段逻辑会把"My"的首字母M和"John"的所有大写首字母拼成"MJohn",完全不符合预期。
修正后的完整可运行代码
保留你已经跑通的年龄提取逻辑,只替换错误的人名提取部分即可:
using System; using System.Linq; static void Main(string[] args) { Console.Write("Name and age: "); string input = Console.ReadLine().Trim(); string ageStr = string.Empty; // 原有年龄提取逻辑无需修改 for (int i = 0; i < input.Length; i++) { if (Char.IsDigit(input[i])) ageStr += input[i]; } // 替换原有的错误大写字符提取逻辑 char[] separators = {' ', '.', ',', '!', '?', ';'}; // 按常见分隔符拆分单词,自动过滤空片段 string[] allWords = input.Split(separators, StringSplitOptions.RemoveEmptyEntries); string targetName = string.Empty; foreach (string word in allWords) { // 逐项匹配校验规则 bool startWithUpper = Char.IsUpper(word[0]); bool lengthValid = word.Length >= 3 && word.Length <= 99; if (startWithUpper && lengthValid) { targetName = word; break; // 示例场景只有一个目标人名,匹配到即退出;如果要匹配多个人名,移除break、改为累加拼接即可 } } Console.WriteLine($"Your name is {targetName}"); Console.WriteLine($"You are {ageStr} years old"); Console.ReadLine(); }
运行效果验证
拿示例输入My name is John and i am 20 years old.测试时:
- 拆分得到的单词列表为
My, name, is, John, and, i, am, 20, years, old - 逐个校验规则:
- My长度为2,不满足长度要求
- 其余小写开头的单词不符合大写开头要求
- 只有John完全匹配「大写开头、长度在3-99区间」的规则
最终输出和预期完全一致:
Your name is John You are 20 years old
简化写法参考
如果觉得逐段遍历的代码太冗余,可以用正则直接匹配符合规则的单词,匹配规则
[A-Z][a-zA-Z]{2,98}刚好对应「大写开头、总长度3-99」的要求,核心提取代码可以简化为:using System.Text.RegularExpressions; Match nameMatch = Regex.Match(input, @"[A-Z][a-zA-Z]{2,98}"); string targetName = nameMatch.Success ? nameMatch.Value : string.Empty;
内容的提问来源于stack exchange,提问作者Cloze Line
相关产品推荐
相关产品推荐

