You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:57:00