如何定义C#方法按输入次数输出带空格分隔的多个hello字符串
你使用的string.Concat方法只会将多个字符串直接拼接,不会自动插入分隔符,因此多个hello之间没有空格。
将string.Concat替换为string.Join方法,指定空格作为分隔符即可,根据你要求的返回格式调整后代码如下:
// 匹配 [次数]: hello hello hello 格式要求 return $"{num}: {string.Join(" ", Enumerable.Repeat("hello", num))}";
如果需要保留你原有代码里的"number of times:"前缀,修改为:
return $"number of times: {string.Join(" ", Enumerable.Repeat("hello", num))}";
补充说明:
string.Join的第一个参数为分隔符,你也可以根据需要替换为其他分隔内容,比如逗号、换行符等- 当输入的num为0时,上述代码会返回
0:(无hello内容),如果需要兼容num为0的特殊场景,可以额外加判断处理
内容的提问来源于stack exchange,提问作者Mnda90
相关产品推荐
相关产品推荐

