1

Ive got an empty string s = "";

Ive got a char b = '0';

char b is in a loop so changes after every, I want to keep adding that char b to the string s,

For example, after the first loop string s = "0" after second round s = "01"

In Java its simple to do that for an empty string with string 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?

8
  • 3
    Use a StringBuilder. Concatenating to a string in a loop is a bad idea as it can cause performance issues from creating a bunch of tempory string objects. Commented Apr 19, 2016 at 14:34
  • is there no other way than a string builder Commented Apr 19, 2016 at 14:35
  • 1
    No "good" way. And why are you so against using StringBuilder? Commented Apr 19, 2016 at 14:36
  • 3
    string += char works in C#, too; if you are having issues please post your exact code. Commented Apr 19, 2016 at 14:36
  • 2
    Same code works for C# too. Commented Apr 19, 2016 at 14:37

2 Answers 2

5

What you describe works in 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.

The same loop as above using 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.
}
Sign up to request clarification or add additional context in comments.

Comments

3

Easy, but not efficient (String s constantly re-creaing):

  char b = '0';

  for (int i = 0; i < n; ++i)
    s += (Char)(b + i);

Better choice is to use StringBuilder:

  char b = '0';

  StringBuilder sb = new StringBuilder(n);

  for (int i = 0; i < n; ++i)
    sb.Append((Char)(b + i));

  s = sb.ToString(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.