首页 > 解决方案 > 制作一根线串

问题描述

我需要帮助我在 c# 中有任务来制作接受用户输入(字符串)的程序。你会得到不同动物发出的噪音,你可以在黑暗中听到,评估每个噪音以确定它属于哪个动物。狮子说“Grr”,老虎说“Rawr”,蛇说“Ssss”,鸟类说“啁啾”。

输入格式:一个字符串,表示您听到的噪音,它们之间有一个空格。

输出格式:一个字符串,其中包含您听到的每种动物,每个动物后面都有一个空格。(动物可以重复)

我做这个

    using System;
    using System.Reflection.Metadata;
    using System.Runtime.CompilerServices;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Text.RegularExpressions;
    
    namespace nekaVjezba
    {
        class Program
        {
            static void Main(string[] args)
            {
    
    
                var text = Console.ReadLine();
    
                var matches = Regex.Matches(text, @"\w+[^\s]*\w+|\w");
               
    
    
                foreach (Match match in matches)
                {
                    var word = match.Value;
    
    
                     if (word == "Grr")
                          {
                        Console.WriteLine("Lion");
    
    
                    }
                          else if (word == "Rawr")
                          {
                        Console.WriteLine("Tiger");
    
                    }
                          else if (word == "Ssss")
                          {
                              Console.WriteLine("Snake");
                          }
                          else if (word == "Chirp")
                          {
                              Console.WriteLine("Bird");
                          }
                }
            }
        }
    }

那是工作,但我的输出是

但应该是在一条线上 Lion Lion Tiger Snake

标签: c#.net

解决方案


有几种方法可以改善这一点,但最简单的建议可能是构建单个输出字符串,添加到它并在单个语句中将其写入控制台,如下所示(半伪代码):

//Intitialize an output string
var output = "";

foreach(Match match in matches)
//Add to output
If(word== "Grr")
    { outPut += "Lion ";}
      ...
}
//Then after all results are added to the string, print the string
Console.WriteLine(output)

推荐阅读