C#字符计分程序末尾多余加号问题解决咨询
如何移除字符计分程序末尾多余的加号?
我写了一个字符计分程序,输入单词(比如hello)时,程序输出是4 + 1 + 3 + 3 + 1 += 12,但预期应该是4 + 1 + 3 + 3 + 1 = 12——末尾多了个多余的加号。现有C#代码如下:
Console.Write("Give a word: "); string word = Console.ReadLine(); string smallword = word.ToLower(); int sum = 0; foreach (char letter in smallword) { int index = Array.IndexOf(alphabet, letter); int score = scores[index]; sum = sum + score; string addingEverythingTogether = $" {score} +"; Console.Write(addingEverythingTogether); } Console.Write($"= {sum}");
解决方案
方法1:收集分数后用string.Join拼接(推荐)
这种方式避免在循环里处理加号的逻辑,代码更简洁易读,是最省心的实现方式:
Console.Write("Give a word: "); string word = Console.ReadLine(); string smallword = word.ToLower(); int sum = 0; List<string> scoreTexts = new List<string>(); foreach (char letter in smallword) { int index = Array.IndexOf(alphabet, letter); int score = scores[index]; sum += score; scoreTexts.Add(score.ToString()); } // 用" + "连接所有分数,再拼接等号和总和 Console.WriteLine($" {string.Join(" + ", scoreTexts)} = {sum}");
方法2:循环中判断是否为最后一个字符
通过跟踪当前字符的索引,判断是否是最后一个,最后一个字符只输出分数不输出加号:
Console.Write("Give a word: "); string word = Console.ReadLine(); string smallword = word.ToLower(); int sum = 0; int totalLetters = smallword.Length; int currentPos = 0; foreach (char letter in smallword) { currentPos++; int index = Array.IndexOf(alphabet, letter); int score = scores[index]; sum += score; if (currentPos == totalLetters) { Console.Write($" {score}"); } else { Console.Write($" {score} +"); } } Console.Write($" = {sum}");
方法3:单独处理第一个字符,后续字符先加再输出
先输出第一个分数,之后的每个字符先输出加号再输出分数,自然不会出现末尾多余加号:
Console.Write("Give a word: "); string word = Console.ReadLine(); string smallword = word.ToLower(); // 处理空输入的情况 if (string.IsNullOrWhiteSpace(smallword)) { Console.WriteLine("= 0"); return; } int sum = 0; // 输出第一个分数 char firstChar = smallword[0]; int firstIndex = Array.IndexOf(alphabet, firstChar); int firstScore = scores[firstIndex]; sum += firstScore; Console.Write($" {firstScore}"); // 处理剩余字符 for (int i = 1; i < smallword.Length; i++) { char letter = smallword[i]; int index = Array.IndexOf(alphabet, letter); int score = scores[index]; sum += score; Console.Write($" + {score}"); } Console.Write($" = {sum}");
内容的提问来源于stack exchange,提问作者laboonx
相关产品推荐
相关产品推荐

