C# String

The string type represents a number of characters and is broadly used in programs. Here are some points to be taken care of when using strings.

  • Using + operator to concatenate strings. For example, string test = "Hello" + "World!".
  • The contents of a string cannot be changed and if it is changed in programs, a new string object will be created actually behind the scenes and the old one will lose its reference and is eligible for garbage collection. So strings are called immutable.
  • The equality operator, == or !=, is used to compare the contents of string objects rather than the string references.

Example 01-82-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;

class Test
{
    static void Main()
    {
        string a = "hello";
        string b = "hello";
        string c = "h";
        c += "ello";

        Console.WriteLine("a==b: {0}", (object)a == (object)b);
        Console.WriteLine("a==c: {0}", (object)a == (object)c);
        Console.WriteLine("a==c: {0}", a == c);
        Console.Read();
    }
}

Output

a==b: True
a==c: False
a==c: True

Explanation

  • Line 7-9: Declare 3 string variables and initialize them with 3 string objects.
  • Line 10: Concatenate the strings "h", "ello" and generate a new string object "hello" to be assigned to c. The string object "h" lost its reference c and is eligible to be collected.
  • Line 12: a and b point to the same object "hello" so they are equivalent. For details, you can check the example 01-21-02 in String Literals.
  • Line 13: c points a new string object created in line 10 so a does not equal to b. The casting (object) is used to make sure the comparison is on the reference level.
  • Line 14: When comparing 2 strings, the contents of the strings are compared actually. a and c point to the different string object "hello" but the same content. So a == c returns true.

A string is a sequential collection of Unicode characters which own char type. Thus, each character can be accessed in a foreach loop statement and an individual character can be read only accessed by [] operator with its sequential index.

Example 01-82-02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;

class Test
{
    static void Main()
    {
        char[] ca = {'G', 'o', 'o', '\u0064', ' ', 'M', 'o', 'r', 'n', 'i', 'n', 'g', '!'};
        string s = new string(ca);
        char c = s[5];
        Console.WriteLine("s: {0}", s);
        Console.WriteLine("c: {0}", c);

        foreach (char ch in s)
        {
            Console.Write("{0} ", ch);
        }
        Console.WriteLine();

        Console.Read();
    }
}

Output

s: Good Morning!
c: M
G o o d   M o r n i n g ! 

Explanation

  • Line 7: Declare a char array with its initialization. \u0064 is an Unicode of a character and represents the character 'd'.
  • Line 8: A string object is created by new operator with the char array as the argument. This is the good way to convert a char array to a string.
  • Line 9: s[5] returns a char type character which represents the sixth character in the string s and it is read only.
  • Line 13: Loop each character in the string and output it.

The keyword string is actually an alias of the class System.String in the .NET Framework. The following is the string methods which are mostly used in programs. We assume declaring a string s used in the table.

MethodsReturnsExamples (string s = "abcdefg";)Results
s.Equals(String)true if the 2 strings have the same value otherwise false.bool result = s.Equals("ABCDEFG");false
s.IndexOf(Char)the index of Char in s or -1 if Char is not found.int result = s.IndexOf('b');1
s.IndexOf(String)the index of String in s or -1 if String is not found.int result = s1.IndexOf("Ab");-1
string.IsNullOrEmpty(s)true if s is null or an empty string otherwise false.bool result=string.IsNullOrEmpty(s);false
string.IsNullOrWhiteSpace(s)true only when s is null, empty or white-space charactersbool result=string.IsNullOrWhiteSpace(s)false
s.Replace(Old, New)A string after replacing the Old with the New in s.string result = s.Replace("bcdef", "");ag
s.Split(Char[])A string array delimited by any element of Char[] in s.string[] result = s.Split(new char[]{'c','e'});{"ab","d","fg"}
s.Substring(i, j)A sub string starting from i index and length j of s.string result = s.Substring(1,2);bc
s.Substring(i)A sub string starting from i index to the end of s.string result = s.Substring(4);efg
s.ToLower()A lowercase string of s.string result = s.ToLower();abcdefg
s.ToUpper()A uppercase string of s.string result = s.ToUpper();ABCDEFG
s.Trim()A string which removes all leading and trailing white-space characters from s.string result = s.Trim();abcdefg

Example 01-82-03

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;

class Test
{
    static void Main()
    {
        // Test Trim()
        string s = " aBCd9 ";
        Console.WriteLine("s=\"{0}\"", s);
        s = s.Trim();
        Console.WriteLine("s=\"{0}\"", s);

        // Test ToLower(), ToUpper() and SubString()
        Console.WriteLine("s.ToLower()={0}", s.ToLower());
        Console.WriteLine("s.ToUpper()={0}", s.ToUpper());
        Console.WriteLine("s.Substring(1, 3)={0}", s.Substring(1, 3));
        Console.WriteLine("s.Substring(2)={0}", s.Substring(2));

        // Test IndexOf() and Replace()
        Console.WriteLine("s.IndexOf('B')={0}", s.IndexOf('B'));
        Console.WriteLine("s.IndexOf(\"AB\")={0}", s.IndexOf("AB"));
        Console.WriteLine("s.Replace(\"BCd\",\"XXX\")={0}", s.Replace("BCd","XXX"));

        // Test Split()
        s = "AxBCXDEFXGHIJxK";
        string[] ss = s.Split(new char[]{'x','X'});
        foreach (string st in ss)
        {
            Console.Write("{0}\t", st);
        }
        Console.WriteLine();
        Console.Read();
    }
}

Output

s=" aBCd9 "
s="aBCd9"
s.ToLower()=abcd9
s.ToUpper()=ABCD9
s.Substring(1, 3)=BCd
s.Substring(2)=Cd9
s.IndexOf('B')=1
s.IndexOf("AB")=-1
s.Replace("BCd","XXX")=aXXX9
A	BC	DEF	GHIJ	K

Explanation

  • Line 10: The leading and trailing space character are removed.
  • Line 21: Returns -1 because "AB" cannot be found in s.
  • Line 26: x or X is the delimiter to split the string s into an array ss.
  • Line 27-30: Loop and output each string in the array ss.

string.Empty is a static read-only field which represents an empty string "". string.Length represents the amount of the characters in the string.

Example 01-82-04

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;

class Test
{
    static void Main()
    {
        string s1 = string.Empty;
        string s2 = "";
        string s3 = null;
        string s4 = " ";

        // Test Length
        Console.WriteLine("s1.Length={0}", s1.Length);
        Console.WriteLine("s2.Length={0}", s2.Length);
        //Console.WriteLine("s3.Length={0}", s3.Length);   Ilegal because of null
        Console.WriteLine("s4.Length={0}", s4.Length);

        // Test Equals()
        Console.WriteLine("s1.Equals(s2)={0}", s1.Equals(s2));
        Console.WriteLine("s1.Equals(s3)={0}", s1.Equals(s3));
        Console.WriteLine("s1.Equals(s4)={0}", s1.Equals(s4));

        // Test string.IsNullOrEmpty(s)
        Console.WriteLine("string.IsNullOrEmpty(s1)={0}", string.IsNullOrEmpty(s1));
        Console.WriteLine("string.IsNullOrEmpty(s2)={0}", string.IsNullOrEmpty(s2));
        Console.WriteLine("string.IsNullOrEmpty(s3)={0}", string.IsNullOrEmpty(s3));
        Console.WriteLine("string.IsNullOrEmpty(s4)={0}", string.IsNullOrEmpty(s4));

        // Test string.IsNullOrWhiteSpace(s)
        Console.WriteLine("string.IsNullOrWhiteSpace(s1)={0}", string.IsNullOrWhiteSpace(s1));
        Console.WriteLine("string.IsNullOrWhiteSpace(s2)={0}", string.IsNullOrWhiteSpace(s2));
        Console.WriteLine("string.IsNullOrWhiteSpace(s3)={0}", string.IsNullOrWhiteSpace(s3));
        Console.WriteLine("string.IsNullOrWhiteSpace(s4)={0}", string.IsNullOrWhiteSpace(s4));
        Console.Read();
    }
}

Output

s1.Length=0
s2.Length=0
s4.Length=1
s1.Equals(s2)=True
s1.Equals(s3)=False
s1.Equals(s4)=False
string.IsNullOrEmpty(s1)=True
string.IsNullOrEmpty(s2)=True
string.IsNullOrEmpty(s3)=True
string.IsNullOrEmpty(s4)=False
string.IsNullOrWhiteSpace(s1)=True
string.IsNullOrWhiteSpace(s2)=True
string.IsNullOrWhiteSpace(s3)=True
string.IsNullOrWhiteSpace(s4)=True

Explanation

  • Line 15: null.Length will generate an error when the program is running. There is no property of null.
  • Line 20: String.Empty or "" does not equal to null.
  • Line 27: " " has a space character so it is not empty.
  • Line 33: string.IsNullOrWhiteSpace(s4) returns true because s4 contains only a space character.

The method Console.WriteLine or Console.Write is often used to print formatted strings. String.Format can save the formatted string to a variable instead of printing out right away.

Example 01-82-05

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;

class Test
{
    static void Main()
    {
        // A simple test
        string s1 = "This";
        string s2 = "Test!";
        string s = string.Format("{0} is a {1}", s1, s2);
        Console.WriteLine(s);

        // A Complicated One
        string[] name = { "Rob", "Mike", "Steve" };
        DateTime[] workStart = { new DateTime(2001, 2, 2), new DateTime(2005, 7, 21), new DateTime(2013, 12, 20) };
        decimal[] salary = { 5005.21M, 3575.97M, 2012.88M };

        string record = string.Format("{0, -6}{1,14:d}{2,12:C}\r\n", "Name", "Start Date", "Salary");
        record += "----------------------------------\r\n";
        for (int i = 0; i < 3; i++)
        {
            record += string.Format("{0, -6}{1, 14:d}{2, 12:C}\r\n", name[i], workStart[i], salary[i]);
        }
        Console.Write(record);

        Console.Read();
    }
}

Output

This is a Test!
Name      Start Date      Salary
----------------------------------
Rob         2/2/2001   $5,005.21
Mike       7/21/2005   $3,575.97
Steve     12/20/2013   $2,012.88

Explanation

  • Line 10: Create a new string object by string.Format method.
  • Line 14-16: Create 3 arrays.
  • Line 18: Save the titles to string record.
  • Line 20-23: Save the formatted data to string record one by one. 6 in {0, -6} means the total length of the string name[i] to be occupied. The negative number means it is left-aligned. The positive number 14 in {1, 14:d} means it is right-aligned and will occupy 14 character. d means the date workStart[i] outputs in short date pattern. {2, 12:C} means salary[i] outputs in the format of 12 width, right-aligned and currency value. For details, please check it here in Microsoft MSDN site.