String concatanation

In this chapter you will learn:

  1. Use the Concat() method to concatenate strings
  2. Use the addition operator (+) to concatenate strings
  3. Concat method with a String array
  4. Mix string and integer in string cancatenation

Use the Concat() method to concatenate strings

using System;/* j  ava2s.c o  m*/

class MainClass
{

  public static void Main()
  {
    string myString4 = String.Concat("A, ", "B");
    Console.WriteLine(myString4);
    string myString5 = String.Concat("A, ", "B, ", "and countrymen");
    Console.WriteLine(myString5);
  }

}

Use the addition operator (+) to concatenate strings

C# reuses the + for string concatenation.

using System;//  j a v a 2s. c  o m

class MainClass
{

  public static void Main()
  {
    string myString6 = "To be, " + "or not to be";
    Console.WriteLine("\"To be, \" + \"or not to be\" = " + myString6);
  }

}

Be careful when appending more than one variables to a string.

string s1 = "abc";
string s2 = s1 + 5 + 5;
Console.WriteLine(s2);

The output:

To get the result we want, we have to do the math first.

string s1 = "abc";
string s2 = s1 + (5 + 5);
Console.WriteLine(s2);

The output:

Concat method with a String array

using System;//from ja  v  a  2  s  .  co m

public class ConcatTest {
    public static void Main() {
        string [] s = { "hello ", "and ", "welcome ", "to ", "this ", "demo! " };

        Console.WriteLine(string.Concat(s));

        Array.Sort(s);
        Console.WriteLine(string.Concat(s));
    }
}

Mix string and integer in string cancatenation

using System;  /* j  a v a  2s.  c  o m*/

class MainClass {  
  public static void Main() {  

    string result = String.Concat("hello ", 88, " ", 20.0, " ", 
                           false, " ",  23.45M);  
    Console.WriteLine("result: " + result);  
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Use the Copy() method to copy a string
  2. Check the equality for copied strings
  3. Copy sub string
Home » C# Tutorial » String
string
String creation
Char in string
Compare strings
String equality
String concatanation
String copy
String Join
String split
String Search for Index
String contains
String start with
String insert
String case
Replacing substring
Remove from a string
Substring
Escape Characters
String verbatim
String padding
Switch on String
String trim
String intern
String normalization
Empty String