C # adding a line to another line

Possible duplicate:
What is the best string concatenation method using C #?

I have a variable:

string variable1; 

And I'm trying to do something like this:

 for (int i = 0; i < 299; i += 2) { variable1 = variable1 && IntToHex(buffer[i]); } 

IntToHex is a string function, so the result of "IntToHex (buffer [i])" will be a string. But an error occurs: I cannot use & &. Is there a solution to add a line to another line? Thanks!

+4
source share
7 answers

Just use the + operator:

 variable1 = variable1 + IntToHex(buffer[i]); 

You also need to initialize variable1 :

 string variable1 = string.Empty; 

or

 string variable1 = null; 

However, use StringBuilder , as this is more efficient:

 StringBuilder builtString = new StringBuilder(); for (int i = 0; i < 299; i += 2) { builtString.Append(IntToHex(buffer[i])); } string variable1 = builtString.ToString(); 
+11
source

In C #, just use + to concatenate strings:

  variable1 = variable1 + IntToHex(buffer[i]); 

But more importantly, this situation requires StringBuilder.

  var buffer = new StringBuilder(); for (int i = 0; i < 299; i += 2) { buffer.Append( IntToHex(buffer[i]) ); } string variable1 = buffer.ToString(); 

For loops of 100 or more, this really greatly affects performance.

+3
source
 variable1 = variable1 + IntToHex(buffer[i]); 

However, this is probably better:

 var sb = new StringBuilder(); for (int i = 0; i < 299; i += 2) { sb.Append(IntToHex(buffer[i])); } variable1 = sb.ToString(); 
+2
source

&& is a conditional AND operator.

You can use the + operator to concatenate strings, but it is not recommended to use this in a loop (more) .

Use either StringBuilder :

 StringBuilder builder = new StringBuilder(299 * 4); // Or whatever for (int i = 0; i < 299; i += 2) { builder.Append(IntToHex(buffer[i])); } string combined = builder.ToString(); 

Or potentially use string.Join - it may not be so practical in this case, considering your loop, but in other cases it would be great. You can still use it here, for example:

 string combined = string.Join("", Enumerable.Range(0, 149) .Select(i => IntToHex(buffer[i * 2]))); 
+2
source
 variable1 += IntToHex(buffer[i]); 
+1
source

There are various ways to add a string to a string. you can use a simple + function, which is not recommended in most cases. string.concat and string.format are the preferred ways to add strings. also the stringBuilder class is useful when adding large parts of strings together

0
source

You need to use + to concatenate strings in C #

 for (int i = 0; i < 299; i += 2) { variable1 = variable1 + IntToHex(buffer[i]); } 

But StringBuilder would be a good option here ...

 StringBuilder sb = new StringBuilder(""); for (int i = 0; i < 299; i += 2) { sb= sb.Append(IntToHex(buffer[i])); } 
0
source

Source: https://habr.com/ru/post/1432064/


All Articles