String concatanation
In this chapter you will learn:
- Use the Concat() method to concatenate strings
- Use the addition operator (+) to concatenate strings
- Concat method with a String array
- 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:
Home » C# Tutorial » String