[英]Add char to empty string C#
Ive got an empty string s = "";我有一个空字符串 s = "";
Ive got a char b = '0';我有一个字符 b = '0';
char b is in a loop so changes after every, I want to keep adding that char b to the string s, char b 处于循环中,因此每次都会更改,我想继续将该 char b 添加到字符串 s,
For example, after the first loop string s = "0" after second round s = "01"例如,在第一个循环字符串 s = "0" 之后,第二个循环 s = "01"
In Java its simple to do that for an empty string with string s += char b;在 Java 中,对字符串 s += char b 的空字符串执行此操作很简单; Couldnt find anything like that on C#, is there an easier way than building a string builder or making a dummy string?
在 C# 上找不到类似的东西,有没有比构建字符串生成器或制作虚拟字符串更简单的方法?
What you describe works in C#:您所描述的内容在 C# 中有效:
string x = "";
x += 'Z';
Console.WriteLine(x); // Prints "Z"
Or in a loop:或者在一个循环中:
string x = "";
char b = '@';
for (int i = 0; i < 10; ++i)
{
++b;
x += b;
Console.WriteLine(x); // Prints "A", then "AB", then "ABC" etc.
}
However, you should use StringBuilder
for efficiency.但是,您应该使用
StringBuilder
来提高效率。
The same loop as above using StringBuilder
:使用
StringBuilder
与上述相同的循环:
StringBuilder x = new StringBuilder();
char b = '@';
for (int i = 0; i < 10; ++i)
{
++b;
x.Append(b);
Console.WriteLine(x); // Prints "A", then "AB", then "ABC" etc.
}
Easy, but not efficient (String s
constantly re-creaing ):简单,但效率不高(String
s
不断重新创建):
char b = '0';
for (int i = 0; i < n; ++i)
s += (Char)(b + i);
Better choice is to use StringBuilder
:更好的选择是使用
StringBuilder
:
char b = '0';
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
sb.Append((Char)(b + i));
s = sb.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.