String Operations


The Length Property

Like an array, the string class has a Length property. The next program uses Length.

// String2 - The Length Property

using System;

class Program
{
    static void Main()
    {
        string hello = "Hello world";
        Console.WriteLine("\"{0}\" has length: {1}", hello, hello.Length);
        Console.WriteLine(hello[0]);
    }
}

The output of the program is as follows.

"Hello world" has length: 11
H

From the output it is apparent that the Length property delivers the number of characters in the string, not including the null-terminator.

The String Indexer

As the previous example preempts, the string class has an indexer. The indexer is a zero-based, readonly indexer. Characters can be read from the string but the string cannot be updated through this indexer. hello[0] delivers the first character in the string - which is 'H'.

Other String Methods

Some other methods of the string class are shown in the table below.

static string Copy(string s) Copies a string.
int CompareTo(string s) Compares the current string with the specified string. If the current string is less than the specified string, less than zero is returned. If the current string is greater than the specified string, greater than zero is returned. If the strings are equal, zero is returned.
int IndexOf(string s) Searches for the substring specified by argument s. If s is found, the index of the first occurrence of the substring is returned. If s is not found, -1 is returned.
int LastIndexOf(string s) Searches for the last occurrence of the substring specified by argument s. If s is found, the index of the last occurrence of the substring is returned. If s is not found, -1 is returned.
string ToLower() Returns the string mapped into lower case.
string ToUpper() Returns the string mapped into upper case.

Equality and Inequality

String equality (==) and inequality operators (!=) are defined. These compare the contents of two strings. For example, the following program uses equality and inequality.

// String3 - Equality and Inequality

using System;

class Program
{
    static void Main()
    {
        string A = "Hello world";
        string B = "Goodbye world";
        string C = "Hello world";

        if (A != B)
            Console.WriteLine("{0} != {1}", A, B);

        if (A == C)
            Console.WriteLine("{0} == {1}", A, C);
    }
}

The output of the program is as follows.

Hello world != Goodbye world
Hello world == Hello world