如何定义一个返回
的方法"[重复次数]:hello hello hello[重复次数]";
我想让它输入hello的次数和我输入的次数一样多
所以,"次数"会在那里,但我不知道怎么打招呼。
我的建议是,
return $"number of times: {string.Concat(Enumerable.Repeat("hello", num))}";
但是我在这里遇到的问题是hello之间没有空格。
你能帮我吗?我已经找了好几个小时了,但还是没有找到类似的答案。
差不多了,使用String。连接而不是字符串。Concat,它允许您在元素
之间添加" "
作为分隔符return $"number of times: {string.Join(" ", Enumerable.Repeat("hello", num))}";
String对象不可变。每次使用系统中的一个方法时。类中,您在内存中创建一个新的字符串对象,这需要为该新对象分配新的空间。在需要对字符串执行重复修改的情况下,与创建新string对象相关的开销可能非常大。System.Text.StringBuilder类可以在不创建新对象的情况下修改字符串时使用。
所以我推荐这个
StringBuilder sb = new StringBuilder($"number of times: {num} = hello");
for (int i = 0; i < num-1; i++) sb.Append( ", hello");
Console.WriteLine(sb.ToString());
number =12
number of times: 12 = hello, hello, hello, hello, hello, hello, hello, hello, hello, hello, hello, hello