Partager via


Using Strings (C# Programming Guide) 

A C# string is an array of characters declared using the string keyword. A string literal is declared using quotation marks, as shown in the following example:

string s = "Hello, World!";

You can extract substrings, and concatenate strings, like this:

string s1 = "orange";
string s2 = "red";

s1 += s2;
System.Console.WriteLine(s1);  // outputs "orangered"

s1 = s1.Substring(2, 5);
System.Console.WriteLine(s1);  // outputs "anger"

String objects are immutable, meaning that they cannot be changed once they have been created. Methods that act on strings actually return new string objects. In the previous example, when the contents of s1 and s2 are concatenated to form a single string, the two strings containing "orange" and "red" are both unmodified. The += operator creates a new string that contains the combined contents. The result is that s1 now refers to a different string altogether. A string containing just "orange" still exists, but is no longer referenced when s1 is concatenated.

Therefore, for performance reasons, large amounts of concatenation or other involved string manipulation should be performed with the StringBuilder class, like this:

System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("one ");
sb.Append("two ");
sb.Append("three");
string str = sb.ToString();

The StringBuilder class is discussed further in the "Using Stringbuilder" section.

Working with Strings

Escape Characters

Escape characters such as "\n" (new line) and "\t" (tab) can be included in strings. The line:

string hello = "Hello\nWorld!";

is the same as:

Hello

World!

If you want to include a backward slash, it must be preceded with another backward slash. The following string:

string filePath = "\\\\My Documents\\";

is actually the same as:

\\My Documents\

The @ Symbol

The @ symbol tells the string constructor to ignore escape characters and line breaks. The following two strings are therefore identical:

string p1 = "\\\\My Documents\\My Files\\";
string p2 = @"\\My Documents\My Files\";

ToString()

Like all objects derived from Object, strings provide the ToString method, which converts a value to a string. This method can be used to convert numeric values into strings, like this:

int year = 1999;
string msg = "Eve was born in " + year.ToString();
System.Console.WriteLine(msg);  // outputs "Eve was born in 1999"

Accessing Individual Characters

Individual characters contained in a string can be accessed using methods such as SubString(), Replace(), Split() and Trim().

string s3 = "Visual C# Express";

System.Console.WriteLine(s3.Substring(7, 2));         // outputs "C#"
System.Console.WriteLine(s3.Replace("C#", "Basic"));  // outputs "Visual Basic Express"

It is also possible to copy the characters into a character array, like this:

string s4 = "Hello, World";
char[] arr = s4.ToCharArray(0, s4.Length);

foreach (char c in arr)
{
    System.Console.Write(c);  // outputs "Hello, World"
}

Individual characters from a string can be accessed with an index, like this:

string s5 = "Printing backwards";

for (int i = 0; i < s5.Length; i++)
{
    System.Console.Write(s5[s5.Length - i - 1]);  // outputs "sdrawkcab gnitnirP"
}

Changing Case

To change the letters in a string to upper or lower case, use ToUpper() or ToLower(), like this:

string s6 = "Battle of Hastings, 1066";

System.Console.WriteLine(s6.ToUpper());  // outputs "BATTLE OF HASTINGS 1066"
System.Console.WriteLine(s6.ToLower());  // outputs "battle of hastings 1066"

Comparisons

The simplest way to compare two strings is to use the == and != operators, which perform a case-sensitive comparison.

string color1 = "red";
string color2 = "green";
string color3 = "red";

if (color1 == color3)
{
    System.Console.WriteLine("Equal");
}
if (color1 != color2)
{
    System.Console.WriteLine("Not equal");
}

String objects also have a CompareTo() method that returns an integer value based on whether one string is less-than (<)or greater-than (>) another. When comparing strings, the Unicode value is used, and lower case has a smaller value than upper case.

string s7 = "ABC";
string s8 = "abc";

if (s7.CompareTo(s8) > 0)
{
    System.Console.WriteLine("Greater-than");
}
else
{
    System.Console.WriteLine("Less-than");
}

To search for a string inside another string, use IndexOf(). IndexOf() returns -1 if the search string is not found; otherwise, it returns the zero-based index of the first location at which it occurs.

string s9 = "Battle of Hastings, 1066";

System.Console.WriteLine(s9.IndexOf("Hastings"));  // outputs 10
System.Console.WriteLine(s9.IndexOf("1967"));      // outputs -1

Splitting a String into Substrings

Splitting a string into substrings—such as splitting a sentence into individual words—is a common programming task. The Split() method takes a char array of delimiters, for example, a space character, and returns an array of substrings. You can access this array with foreach, like this:

char[] delimit = new char[] { ' ' };
string s10 = "The cat sat on the mat.";
foreach (string substr in s10.Split(delimit))
{
    System.Console.WriteLine(substr);
}

This code outputs each word on a separate line, like this:

The

cat

sat

on

the

mat.

Using StringBuilder

The StringBuilder class creates a string buffer that offers better performance if your program performs a lot of string manipulation. The StringBuilder string also allows you to reassign individual characters, something the built-in string data type does not support. This code, for example, changes the content of a string without creating a new string:

System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet");
sb[0] = 'C';
System.Console.WriteLine(sb.ToString());
System.Console.ReadLine();

In this example, a StringBuilder object is used to create a string from a set of numeric types:

class TestStringBuilder
{
    static void Main()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        // Create a string composed of numbers 0 - 9
        for (int i = 0; i < 10; i++)
        {
            sb.Append(i.ToString());
        }
        System.Console.WriteLine(sb);  // displays 0123456789

        // Copy one character of the string (not possible with a System.String)
        sb[0] = sb[9];

        System.Console.WriteLine(sb);  // displays 9123456789
    }
}

For More Information

From the C# Programmer's Reference:

See Also

Tasks

How to: Search Strings Using Regular Expressions (C# Programming Guide)
How to: Search Strings Using String Methods (C# Programming Guide)
How to: Parse Strings Using the Split Method (C# Programming Guide)

Concepts

C# Programming Guide

Other Resources

Parsing Strings