Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# adding string to another string [duplicate]

Tags:

c#

Possible Duplicate:
What's the best string concatenation method using C#?

I have a variable :

string variable1;

And I'm trying to make 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 the "IntToHex(buffer[i])" will be string. But it comes up to an error saying I cannot use &&. Is there any solution to add a string to another string? Thanks!

like image 275
user1639776 Avatar asked Sep 03 '12 11:09

user1639776


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


2 Answers

Just use the + operator:

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

You also need to initialise variable1:

string variable1 = string.Empty;

or

string variable1 = null;

However consider using a StringBuilder instead as it's more efficient:

StringBuilder builtString = new StringBuilder();

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

string variable1 = builtString.ToString();
like image 169
ChrisF Avatar answered Sep 27 '22 19:09

ChrisF


In C#, simply use a + to concatenate strings:

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

But more important, this kind of situation requires a 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 makes a big difference in performance.

like image 39
Henk Holterman Avatar answered Sep 27 '22 19:09

Henk Holterman