c# - 制作一根线串
问题描述
我需要帮助我在 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
解决方案
有几种方法可以改善这一点,但最简单的建议可能是构建单个输出字符串,添加到它并在单个语句中将其写入控制台,如下所示(半伪代码):
//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)
推荐阅读
- c# - C# - 网络设备列表
- sql - 如何在 redshift 中创建一个表,其中包含与 2 个或 3 个其他表的内连接相关的数据?
- javascript - 将表格中的表单元素作为ajax请求提交?
- sql - 如何在 BigQuery SQL 语法中正确地“作为”应用了“LOWER”函数的列,以便在包装“SELECT”中引用它?
- postgresql - 按字母顺序排序数组元素 PostgreSQL
- mongodb - 如何仅更新 MongoDB 文档中的一个字段
- javascript - 将文字值转换为可观察值的便捷方法
- c - 如何修复“'struct _IO_FILE'没有名为'_file'的成员”?
- python - 使用 pd.Dataframe.isin() 通过多个条件获取新的数据帧
- python - 使用 python 发送电子邮件:如何形成消息?