Mono Class Library: System Namespace

System.String Class

Represents an immutable series of characters. [Edit]

See Also: String Members

[System.Runtime.InteropServices.ComVisible(true)]
public sealed class String : IEnumerable<char>, ICloneable, IComparable, IComparable<string>, IConvertible, IEquatable<string>

Thread Safety

This type is safe for multithreaded operations.

Remarks

An index is the position of a character within a string. The first character in the string is at index 0. The length of a string is the number of characters it is made up of. The last accessible index of a string instance is string.Length - 1.

Strings are immutable; once created, the contents of a string do not change. Combining operations, such as string.Replace(char, char), cannot alter existing strings. Instead, such operations return a new string that contains the results of the operation, an unchanged string, or the null value. To perform modifications to a string use the System.Text.StringBuilder .

Implementations of string are required to contain a variable-length character buffer positioned a fixed number of bytes after the beginning of the String object.

Note: The System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData method returns the number of bytes between the start of the String object and the character buffer. This information is intended primarily for use by compilers, not application programmers. For additional information, see System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData .

Note:

Comparisons and searches are case-sensitive by default, and unless otherwise specified, use the culture defined (if any) for the current thread to determine the order of the alphabet used by the strings. This information is then used to compare the two strings on a character-by-character basis. Upper case letters evaluate greater than their lowercase equivalents.

The following characters are considered white space when present in a string instance: 0x9, 0xA, 0xB, 0xC, 0xD, 0x20, 0xA0, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x200B, 0x3000, and 0xFEFF. The null character is defined as hexadecimal 0x00.

The string(string) constructor is omitted for performance reasons. If you need a copy of a string, consider using string.Copy(string) or the System.Text.StringBuilder class.

To insert a formatted string representation of an object into a string, use the string.Format(string, object) methods. These methods take one or more arguments to be formatted, and a format string. The format string contains literals and zero or more format specifications of the form { N [, M ][: formatSpecifier ]}, where:

  • N is a zero-based integer indicating the argument to be formatted. If the actual argument is a null reference, then an empty string is used in its place.
  • M is an optional integer indicating the minimum width of the region to contain the formatted value of argument N . If the length of the string representation of the value is less than M, then the region is padded with spaces. If M is negative, the formatted value is left justified in the region; if M is positive, then the value is right justified. If M is not specified, it is assumed to be zero indicating that neither padding nor alignment is customized. Note that if the length of the formatted value is greater than M, then M is ignored.
  • formatSpecifier is an optional string that determines the representation used for arguments. For example, an integer can be represented in hexadecimal or decimal format, or as a monetary value. If formatSpecifier is omitted and an argument implements the IFormattable interface, then a null reference is used as the IFormattable.ToString(string, IFormatProvider) format specifier. Therefore, all implementations of IFormattable.ToString(string, IFormatProvider) are required to allow a null reference as a format specifier, and return a string containing the default representation of the object as determined by the object type. For additional information on format specifiers, see IFormattable .

If an object referenced in the format string implements IFormattable, then the IFormattable.ToString(string, IFormatProvider) method of the object provides the formatting. If the argument does not implement IFormattable, then the object.ToString method of the object provides default formatting, and formatSpecifier , if present, is ignored. For an example that demonstrates this, see Example 2.

To include a curly bracket in a formatted string, specify the bracket twice; for example, specify "{{" to include "{" in the formatted string. See Example 1.

The Console class exposes the same functionality as the string.Format(string, object) methods via Console.Write(string, object) and Console.WriteLine. The primary difference is that the string.Format(string, object) methods return the formatted string, while the System.Console methods write the formatted string to a stream.

When a non-empty string is searched for the first or last occurrence of an empty string, the empty string is found at the search start position.

[Edit]

Example

Example 1

The following example demonstrates formatting numeric data types and inserting literal curly brackets into strings.

C# Example
using System;
class StringFormatTest {
    public static void Main() {
        decimal dec = 1.99999m;
        double doub = 1.0000000001;

        string somenums = String.Format("Some formatted numbers: dec={0,15:E} doub={1,20}", dec, doub);
        Console.WriteLine(somenums);

        string curlies = "Literal curly brackets: {{ and }} and {{0}}";
        Console.WriteLine(curlies);

        object nullObject = null;
        string embeddedNull = String.Format("A null argument looks like: {0}", nullObject);
        Console.WriteLine(embeddedNull);
    }
}
   

The output is

Example
Some formatted numbers: dec=  1.999990E+000 doub=        1.0000000001
Literal curly brackets: {{ and }} and {{0}}
A null argument looks like: 
 

Example 2

The following example demonstrates how formatting works if IFormattable is or is not implemented by an argument to the string.Format(string, object) method. Note that the format specifier is ignored if the argument does not implement IFormattable.

C# Example
using System;
class StringFormatTest {
    public class DefaultFormatEleven {
        public override string ToString() {
            return "11 string";
        }
    }
    public class FormattableEleven:IFormattable {
        // The IFormattable ToString implementation.
        public string ToString(string format, IFormatProvider formatProvider) {
            Console.Write("[IFormattable called] ");
            return 11.ToString(format, formatProvider);
        }
        // Override Object.ToString to show that it is not called.
        public override string ToString() {
            return "Formatted 11 string";
        }
    }

    public static void Main() {
        DefaultFormatEleven def11 = new DefaultFormatEleven ();
         FormattableEleven for11 = new  FormattableEleven();
        string def11string = String.Format("{0}",def11);
        Console.WriteLine(def11string);
        // The format specifier x is ignored.
        def11string = String.Format("{0,15:x}", def11);
        Console.WriteLine(def11string);

        string form11string = String.Format("{0}",for11);
        Console.WriteLine(form11string );
        form11string = String.Format("{0,15:x}",for11);
        Console.WriteLine(form11string);
    }
}

The output is

Example
11 string
      11 string
[IFormattable called] 11
[IFormattable called]               b
 

Example 3

The following example demonstrates searching for an empty string in a non-empty string.

C# Example
using System;
class EmptyStringSearch {
	public static void Main() 	{
		Console.WriteLine("ABCDEF".IndexOf(""));
		Console.WriteLine("ABCDEF".IndexOf("", 2));
		Console.WriteLine("ABCDEF".IndexOf("", 3, 2));
		Console.WriteLine("ABCDEF".LastIndexOf(""));
		Console.WriteLine("ABCDEF".LastIndexOf("", 1));
		Console.WriteLine("ABCDEF".LastIndexOf("", 4, 2));
	}
}

The output is

Example
0
2
3
5
1
4

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0