C#提取字符串指定序号单词运行异常 代码逻辑错误排查
问题背景
需求为接收用户输入的一个句子、一个数字序号,返回句子中对应序号的单词。
原实现代码测试时,输入句子为 I have two pens、序号为2,程序逐次输出h、ha、hav、have,无法正确返回目标单词。
原代码如下:
using System; string inputData = Console.ReadLine(); string text = inputData; inputData=Console.ReadLine(); int x = Convert.ToInt32(inputData); string currentWord = String.Empty; int wordCount = 1; for (int i = 0; i < text.Length; ++i) { if (text[i] == ' ') { wordCount++; currentWord = String.Empty; while (text[i] == ' ') i++; } if (text[i] != ' ') { currentWord += text[i]; } if (wordCount == x) Console.WriteLine(currentWord); } Console.Read();
错误点说明
- 输出逻辑位置错误:输出判断放在了逐字符遍历的循环内部,每给当前单词拼接一个字符就会触发一次输出,这就是测试时逐行输出单词前缀的直接原因。
- 序号计数逻辑错位:初始
wordCount设为1,但测试输入的句子开头带有前导空格,第一次遍历到开头的空格时就直接把计数加到2,此时还未读取任何有效单词,序号匹配从一开始就错了。 - 边界判断缺失:跳过连续空格的while循环没有校验索引是否超出字符串长度,句子末尾带空格时会触发索引越界异常;同时遍历到目标单词后没有终止循环,会持续做无意义的后续遍历。
- 末尾单词漏处理:句子最后一个单词后面没有空格,原逻辑里只有遇到空格才会触发计数判断,最后一个单词永远不会被匹配输出。
- 索引步进逻辑错误:跳过连续空格的while循环执行完后,没有回退索引,for循环本身的
++i会直接跳过下一个单词的首字符。
修正后可运行代码
using System; string text = Console.ReadLine(); int targetIndex = Convert.ToInt32(Console.ReadLine()); string currentWord = string.Empty; int wordCount = 0; int i = 0; // 先跳过句子开头的所有前导空格,避免计数错位 while (i < text.Length && text[i] == ' ') { i++; } for (; i < text.Length; i++) { if (text[i] == ' ') { wordCount++; // 匹配到目标单词直接输出,结束逻辑 if (wordCount == targetIndex) { Console.WriteLine(currentWord); return; } currentWord = string.Empty; // 跳过单词间的连续空格,做好边界校验 while (i < text.Length && text[i] == ' ') { i++; } // 回退一位,抵消for循环的i自增,避免漏掉下一个单词首字符 i--; } else { currentWord += text[i]; } } // 补处理句子末尾的最后一个单词 wordCount++; if (wordCount == targetIndex) { Console.WriteLine(currentWord); } Console.Read();
内容的提问来源于stack exchange,提问作者Skike
相关产品推荐
相关产品推荐

