System.String Class

Represents text as a series of Unicode characters.

See Also: String

Syntax

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

Remarks

A string is a sequential collection of Unicode characters that is used to represent text. A String object is a sequential collection of Char objects that represent a string. The value of the String object is the content of the sequential collection, and that value is immutable (that is, it is read-only). For more information about the immutability of strings, see the Immutability and the StringBuilder class section later in this topic. The maximum size of a String object in memory is 2 GB, or about 1 billion characters.

In this section:

Instantiating a String objectChar objects and Unicode charactersStrings and embedded null charactersStrings and indexesNull strings and empty stringsImmutability and the StringBuilder classOrdinal vs. culture-sensitive operationsNormalizationString operations by category

Instantiating a String object

You can instantiate a String object in the following ways:

  • By assigning a string literal to a String variable. This is the most commonly used method for creating a string. The following example uses assignment to create several strings. Note that in C#, because the backslash (\) is an escape character, literal backslashes in a string must be escaped or the entire string must be @-quoted.

    code reference: System.String.Class.Instantiate#1

  • By calling a String class constructor. The following example instantiates strings by calling several class constructors. Note that some of the constructors include pointers to character arrays or signed byte arrays as parameters. Visual Basic does not support calls to these constructors. For detailed information about String constructors, see the erload:System.String.#ctor constructor summary.

    code reference: System.String.Class.Instantiate#2

  • By using the string concatenation operator (+ in C# and & or + in Visual Basic) to create a single string from any combination of String instances and string literals. The following example illustrates the use of the string concatenation operator.

    code reference: System.String.Class.Instantiate#3

  • By retrieving a property or calling a method that returns a string. The following example uses the methods of the String class to extract a substring from a larger string.

    code reference: System.String.Class.Instantiate#4

  • By calling a formatting method to convert a value or object to its string representation. The following example uses the composite formatting feature to embed the string representation of two objects into a string.

    code reference: System.String.Class.Instantiate#5

Char objects and Unicode characters

Each character in a string is defined by a Unicode scalar value, also called a Unicode code point or the ordinal (numeric) value of the Unicode character. Each code point is encoded by using UTF-16 encoding, and the numeric value of each element of the encoding is represented by a Char object.

A single Char object usually represents a single code point; that is, the numeric value of the Char equals the code point. For example, the code point for the character "a" is U+0061. However, a code point might require more than one encoded element (more than one Char object). The Unicode standard defines three types of characters that correspond to multiple Char objects: graphemes, Unicode supplementary code points, and characters in the supplementary planes.

  • A grapheme is represented by a base character followed by one or more combining characters. For example, the character ä is represented by a Char object whose code point is U+0061 followed by a Char object whose code point is U+0308. This character can also be defined by a single Char object that has a code point of U+00E4. As the following example shows, a culture-sensitive comparison for equality indicates that these two representations are equal, although an ordinary ordinal comparison does not. However, if the two strings are normalized, an ordinal comparison also indicates that they are equal. (For more information on normalizing strings, see the Normalization section.)

    code reference: System.String.Class#2

  • A Unicode supplementary code point (a surrogate pair) is represented by a Char object whose code point is a high surrogate followed by a Char object whose code point is a low surrogate. The code units of high surrogates range from U+D800 to U+DBFF. The code units of low surrogates range from U+DC00 to U+DFFF. Surrogate pairs are used to represent characters in the 16 Unicode supplementary planes. The following example creates a surrogate character and passes it to the Char.IsSurrogatePair(Char,Char) method to determine whether it is a surrogate pair.

    code reference: System.String.Class#3

Strings and embedded null characters

In the .NET Framework, a String object can include embedded null characters, which count as a part of the string's length. However, in some languages such as C and C++, a null character indicates the end of a string; it is not considered a part of the string and is not counted as part of the string's length. This means that the following common assumptions that C and C++ programmers or libraries written in C or C++ might make about strings are not necessarily valid when applied to String objects:

  • The value returned by the strlen or wcslen functions does not necessarily equal String.Length.

  • The string created by the strcpy_s or wcscpy_s functions is not necessarily identical to the string created by the String.Copy(String) method.

You should ensure that native C and C++ code that instantiates String objects, and code that is passed String objects through platform invoke, do not assume that an embedded null character marks the end of the string.

Embedded null characters in a string are also treated differently when a string is sorted (or compared) and when a string is searched. Null characters are ignored when performing culture-sensitive comparisons between two strings, including comparisons using the invariant culture. They are considered only for ordinal or case-insensitive ordinal comparisons. On the other hand, embedded null characters are always considered when searching a string with methods such as String.Contains(String), String.StartsWith(String), and String.IndexOf(String).

Strings and indexes

An index is the position of a Char object (not a Unicode character) in a String. An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. A number of search methods, such as String.IndexOf(Char) and String.LastIndexOf(Char), return the index of a character or substring in the string instance.

The String.Chars(Int32) property lets you access individual Char objects by their index position in the string. Because the String.Chars(Int32) property is the default property (in Visual Basic) or the indexer (in C#), you can access the individual Char objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains.

code reference: System.String.Class#4

Because the String class implements the IEnumerable interface, you can also iterate through the Char objects in a string by using a foreach construct, as the following example shows.

code reference: System.String.Class#5

Consecutive index values might not correspond to consecutive Unicode characters, because a Unicode character might be encoded as more than one Char object. In particular, a string may contain multi-character units of text that are formed by a base character followed by one or more combining characters or by surrogate pairs. To work with Unicode characters instead of Char objects, use the StringInfo and TextElementEnumerator classes. The following example illustrates the difference between code that works with Char objects and code that works with Unicode characters. It compares the number of characters or text elements in each word of a sentence. The string includes two sequences of a base character followed by a combining character.

code reference: System.String.Class#6

This example works with text elements by using the StringInfo.GetTextElementEnumerator(String) method and the TextElementEnumerator class to enumerate all the text elements in a string. You can also retrieve an array that contains the starting index of each text element by calling the StringInfo.ParseCombiningCharacters(String) method.

For more information about working with units of text rather than individual Char values, see the StringInfo class.

Null strings and empty strings

A string that has been declared but has not been assigned a value is null. Attempting to call methods on that string throws a NullReferenceException. A null string is different from an empty string, which is a string whose value is "" or String.Empty. In some cases, passing either a null string or an empty string as an argument in a method call throws an exception. For example, passing a null string to the Int32.Parse(String) method throws an ArgumentNullException, and passing an empty string throws a FormatException. In other cases, a method argument can be either a null string or an empty string. For example, if you are providing an IFormattable implementation for a class, you want to equate both a null string and an empty string with the general ("G") format specifier.

The String class includes the following two convenience methods that enable you to test whether a string is null or empty:

  • String.IsNullOrEmpty(String), which indicates whether a string is either null or is equal to String.Empty. This method eliminates the need to use code such as the following:

    code reference: System.String.Class.Null#1

  • String.IsNullOrWhiteSpace(String), which indicates whether a string is null, equals String.Empty, or consists exclusively of white-space characters. This method eliminates the need to use code such as the following:

    code reference: System.String.Class.Null#2

The following example uses the String.IsNullOrEmpty(String) method in the IFormattable.ToString(String,IFormatProvider) implementation of a custom Temperature class. The method supports the "G", "C", "F", and "K" format strings. If an empty format string or a format string whose value is null is passed to the method, its value is changed to the "G" format string.

code reference: System.String.Class.Null#3

Immutability and the StringBuilder class

A String object is called immutable (read-only), because its value cannot be modified after it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification.

Because strings are immutable, string manipulation routines that perform repeated additions or deletions to what appears to be a single string can exact a significant performance penalty. For example, the following code uses a random number generator to create a string with 1000 characters in the range 0x0001 to 0x052F. Although the code appears to use string concatenation to append a new character to the existing string named str, it actually creates a new String object for each concatenation operation.

code reference: System.String.Class#15

You can use the StringBuilder class instead of the String class for operations that make multiple changes to the value of a string. Unlike instances of the String class, StringBuilder objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string. When you have finished modifying the value of a StringBuilder object, you can call its StringBuilder.ToString method to convert it to a string. The following example replaces the String used in the previous example to concatenate 1000 random characters in the range to 0x0001 to 0x052F with a StringBuilder object.

code reference: System.String.Class#16

Ordinal vs. culture-sensitive operations

Members of the String class perform either ordinal or culture-sensitive (linguistic) operations on a String object. An ordinal operation acts on the numeric value of each Char object. A culture-sensitive operation acts on the value of the String object, and takes culture-specific casing, sorting, formatting, and parsing rules into account. Culture-sensitive operations execute in the context of an explicitly declared culture or the implicit current culture. The two kinds of operations can produce very different results when they are performed on the same string.

Note:

If your application makes a security decision about a symbolic identifier such as a file name or named pipe, or about persisted data such as the text-based data in an XML file, the operation should use an ordinal comparison instead of a culture-sensitive comparison. This is because a culture-sensitive comparison can yield different results depending on the culture in effect, whereas an ordinal comparison depends solely on the binary value of the compared characters.

Note:

Most methods that perform string operations include an overload that has a parameter of type StringComparison, which enables you to specify whether the method performs an ordinal or culture-sensitive operation. In general, you should call this overload to make the intent of your method call clear. For best practices and guidance for using ordinal and culture-sensitive operations on strings, see Best Practices for Using Strings in the .NET Framework.

Operations for casing, parsing and formatting, comparison and sorting, and testing for equality can be either ordinal or culture-sensitive. The following sections discuss each category of operation.

Casing

Casing rules determine how to change the capitalization of a Unicode character; for example, from lowercase to uppercase. Often, a casing operation is performed before a string comparison. For example, a string might be converted to uppercase so that it can be compared with another uppercase string. You can convert the characters in a string to lowercase by calling the String.ToLower or String.ToLowerInvariant method, and you can convert them to uppercase by calling the String.ToUpper or String.ToUpperInvariant method. In addition, you can use the TextInfo.ToTitleCase(String) method to convert a string to title case.

Casing operations can be based on the rules of the current culture, a specified culture, or the invariant culture. Because case mappings can vary depending on the culture used, the result of casing operations can vary based on culture. The actual differences in casing are of three kinds:

  • Differences in the case mapping of LATIN CAPITAL LETTER I (U+0049), LATIN SMALL LETTER I (U+0069), LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130), and LATIN SMALL LETTER DOTLESS I (U+0131). In the tr-TR (Turkish (Turkey)) and az-Latn-AZ (Azerbaijan, Latin) cultures, and in the tr, az, and az-Latn neutral cultures, the lowercase equivalent of LATIN CAPITAL LETTER I is LATIN SMALL LETTER DOTLESS I, and the uppercase equivalent of LATIN SMALL LETTER I is LATIN CAPITAL LETTER I WITH DOT ABOVE. In all other cultures, including the invariant culture, LATIN SMALL LETTER I and LATIN CAPITAL LETTER I are lowercase and uppercase equivalents.

    The following example demonstrates how a string comparison designed to prevent file system access can fail if it relies on a culture-sensitive casing comparison. (The casing conventions of the invariant culture should have been used.)

    code reference: System.String.Class#17

  • Differences in case mappings between the invariant culture and all other cultures. In these cases, using the casing rules of the invariant culture to change a character to uppercase or lowercase returns the same character. For all other cultures, it returns a different character. Some of the affected characters are listed in the following table.

  • Differences in case mappings of two-letter mixed-case pairs in the ASCII character range. In most cultures, a two-letter mixed-case pair is equal to the equivalent two-letter uppercase or lowercase pair. This is not true for the following two-letter pairs in the following cultures, because in each case they are compared to a digraph:

    However, it is unusual to encounter a situation in which a culture-sensitive comparison of these pairs creates problems, because these pairs are uncommon in fixed strings or identifiers.

The following example illustrates some of the differences in casing rules between cultures when converting strings to uppercase.

code reference: System.String.Class#7

Parsing and formatting

Formatting and parsing are inverse operations. Formatting rules determine how to convert a value, such as a date and time or a number, to its string representation, whereas parsing rules determine how to convert a string representation to a value such as a date and time. Both formatting and parsing rules are dependent on cultural conventions. The following example illustrates the ambiguity that can arise when interpreting a culture-specific date string. Without knowing the conventions of the culture that was used to produce a date string, it is not possible to know whether 03/01/2011, 3/1/2011, and 01/03/2011 represent January 3, 2011 or March 1, 2011.

code reference: System.String.Class#8

Similarly, as the following example shows, a single string can produce different dates depending on the culture whose conventions are used in the parsing operation.

code reference: System.String.Class#9

String comparison and sorting

Sort rules determine the alphabetic order of Unicode characters and how two strings compare to each other. For example, the String.Compare(String,String,StringComparison) method compares two strings based on the StringComparison parameter. If the parameter value is StringComparison.CurrentCulture, the method performs a linguistic comparison that uses the conventions of the current culture; if the parameter value is StringComparison.Ordinal, the method performs an ordinal comparison. Consequently, as the following example shows, if the current culture is U.S. English, the first call to the String.Compare(String,String,StringComparison) method (using culture-sensitive comparison) considers "a" less than "A", but the second call to the same method (using ordinal comparison) considers "a" greater than "A".

code reference: System.String.Class#10

The .NET Framework supports word, string, and ordinal sort rules:

  • A word sort performs a culture-sensitive comparison of strings in which certain nonalphanumeric Unicode characters might have special weights assigned to them. For example, the hyphen (-) might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. For a list of the String methods that compare two strings using word sort rules, see the String operations by category section.

  • A string sort also performs a culture-sensitive comparison. It is similar to a word sort, except that there are no special cases, and all nonalphanumeric symbols come before all alphanumeric Unicode characters. Two strings can be compared using string sort rules by calling the CompareInfo.Compare(String,String) method overloads that have an options parameter that is supplied a value of CompareOptions.StringSort. Note that this is the only method that the .NET Framework provides to compare two strings using string sort rules.

  • An ordinal sort compares strings based on the numeric value of each Char object in the string. An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. However, if case is not important, you can specify an ordinal comparison that ignores case. This is equivalent to converting the string to uppercase by using the invariant culture and then performing an ordinal comparison on the result. For a list of the String methods that compare two strings using ordinal sort rules, see the String operations by category section.

A culture-sensitive comparison is any comparison that explicitly or implicitly uses a CultureInfo object, including the invariant culture that is specified by the CultureInfo.InvariantCulture property. The implicit culture is the current culture, which is specified by the Thread.CurrentCulture and CultureInfo.CurrentCulture properties. There is considerable variation in the sort order of alphabetic characters (that is, characters for which the Char.IsLetter(Char) property returns true) across cultures. You can specify a culture-sensitive comparison that uses the conventions of a specific culture by supplying a CultureInfo object to a string comparison method such as String.Compare(String,String,CultureInfo,CompareOptions). You can specify a culture-sensitive comparison that uses the conventions of the current culture by supplying StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase, or any member of the CompareOptions enumeration other than CompareOptions.Ordinal or CompareOptions.OrdinalIgnoreCase to an appropriate overload of the String.Compare(String,String) method. A culture-sensitive comparison is generally appropriate for sorting whereas an ordinal comparison is not. An ordinal comparison is generally appropriate for determining whether two strings are equal (that is, for determining identity) whereas a culture-sensitive comparison is not.

Use the following general guidelines to choose an appropriate sorting or string comparison method:

  • If you want the strings to be ordered based on the user's culture, you should order them based on the conventions of the current culture. If the user's culture changes, the order of sorted strings will also change accordingly. For example, a thesaurus application should always sort words based on the user's culture.

  • If you want the strings to be ordered based on the conventions of a specific culture, you should order them by supplying a CultureInfo object that represents that culture to a comparison method. For example, in an application designed to teach students a particular language, you want strings to be ordered based on the conventions of one of the cultures that speaks that language.

  • If you want the order of strings to remain unchanged across cultures, you should order them based on the conventions of the invariant culture or use an ordinal comparison. For example, you would use an ordinal sort to organize the names of files, processes, mutexes, or named pipes.

  • For a comparison that involves a security decision (such as whether a user name is valid), you should always perform an ordinal test for equality by calling an overload of the String.Equals(String) method.

Note:

The culture-sensitive sorting and casing rules used in string comparison depend on the version of the .NET Framework. In the net_v45 running on the win8 operating system, sorting, casing, normalization, and Unicode character information conforms to the Unicode 6.0 standard. On other operating systems, it conforms to the Unicode 5.0 standard.

For more information about word, string, and ordinal sort rules, see the CompareOptions topic. For additional recommendations on when to use each rule, see Best Practices for Using Strings in the .NET Framework.

Ordinarily, you do not call string comparison methods such as String.Compare(String,String) directly to determine the sort order of strings. Instead, comparison methods are called by sorting methods such as Array.Sort(Array) or List`1.Sort. The following example performs four different sorting operations (word sort using the current culture, word sort using the invariant culture, ordinal sort, and string sort using the invariant culture) without explicitly calling a string comparison method. Note that each type of sort produces a unique ordering of strings in its array.

code reference: System.String.Class#12

Note:

If your primary purpose in comparing strings is to determine whether they are equal, you should call the String.Equals(Object) method. Typically, you should use String.Equals(Object) to perform an ordinal comparison. The String.Compare(String,String) method is intended primarily to sort strings.

String search methods, such as String.StartsWith(String) and String.IndexOf(Char), also can perform culture-sensitive or ordinal string comparisons. The following example illustrates the differences between ordinal and culture-sensitive comparisons using the String.IndexOf(Char) method. A culture-sensitive search in which the current culture is English (United States) considers the substring "oe" to match the ligature "œ". Because a soft hyphen (U+00AD) is a zero-width character, the search treats the soft hyphen as equivalent to String.Empty and finds a match at the beginning of the string. An ordinal search, on the other hand, does not find a match in either case.

code reference: System.String.Class#13

Testing for equality

Use the String.Compare(String,String) method to determine the relationship of two strings in the sort order. Typically, this is a culture-sensitive operation. In contrast, call the String.Equals(String) method to test for equality. Because the test for equality usually compares user input with some known string, such as a valid user name, a password, or a file system path, it is typically an ordinal operation.

Note:

It is possible to test for equality by calling the String.Compare(String,String) method and determining whether the return value is zero. However, this practice is not recommended. To determine whether two strings are equal, you should call one of the overloads of the String.Equals(String) method. The preferred overload to call is either the instance String.Equals(String,StringComparison) method or the static String.Equals(String,String,StringComparison) method, because both methods include a StringComparison parameter that explicitly specifies the type of comparison.

The following example illustrates the danger of performing a culture-sensitive comparison for equality when an ordinal one should be used instead. In this case, the intent of the code is to prohibit file system access from URLs that begin with "FILE://" or "file://" by performing a case-insensitive comparison of the beginning of a URL with the string "FILE://". However, if a culture-sensitive comparison is performed using the Turkish (Turkey) culture on a URL that begins with "file://", the comparison for equality fails, because the Turkish uppercase equivalent of the lowercase "i" is "İ" instead of "I". As a result, file system access is inadvertently permitted. On the other hand, if an ordinal comparison is performed, the comparison for equality succeeds, and file system access is denied.

code reference: System.String.Class#11

Normalization

Some Unicode characters have multiple representations. For example, any of the following code points can represent the letter "ắ":

  • U+1EAF

  • U+0103 U+0301

  • U+0061 U+0306 U+0301

Multiple representations for a single character complicate searching, sorting, matching, and other string operations.

The Unicode standard defines a process called normalization that returns one binary representation of a Unicode character for any of its equivalent binary representations. Normalization can use several algorithms, called normalization forms, that follow different rules. The .NET Framework supports Unicode normalization forms C, D, KC, and KD. When strings have been normalized to the same normalization form, they can be compared by using ordinal comparison.

An ordinal comparison is a binary comparison of the Unicode scalar value of corresponding Char objects in each string. The String class includes a number of methods that can perform an ordinal comparison, including the following:

You can determine whether a string is normalized to normalization form C by calling the String.IsNormalized method, or you can call the String.IsNormalized(NormalizationForm) method to determine whether a string is normalized to a specified normalization form. You can also call the String.Normalize method to convert a string to normalization form C, or you can call the String.Normalize(NormalizationForm) method to convert a string to a specified normalization form. For step-by-step information about normalizing and comparing strings, see the String.Normalize and String.Normalize(NormalizationForm) methods.

The following simple example illustrates string normalization. It defines the letter "ố" in three different ways in three different strings, and uses an ordinal comparison for equality to determine that each string differs from the other two strings. It then converts each string to the supported normalization forms, and again performs an ordinal comparison of each string in a specified normalization form. In each case, the second test for equality shows that the strings are equal.

code reference: System.String.Class#14

For more information about normalization and normalization forms, see NormalizationForm, as well as tp://unicode.org/reports/tr15/ and the tp://www.unicode.org/faq/normalization.html on the unicode.org website.

String operations by category

The String class provides members for comparing strings, testing strings for equality, finding characters or substrings in a string, modifying a string, extracting substrings from a string, combining strings, formatting values, copying a string, and normalizing a string.

Comparing strings

You can compare strings to determine their relative position in the sort order by using the following String methods:

Testing strings for equality

You call the String.Equals(String) method to determine whether two strings are equal. The instance String.Equals(String,String,StringComparison) and the static String.Equals(String,StringComparison) overloads let you specify whether the comparison is culture-sensitive or ordinal, and whether case is considered or ignored. Most tests for equality are ordinal, and comparisons for equality that determine access to a system resource (such as a file system object) should always be ordinal.

Finding characters in a string

The String class includes two kinds of search methods:

Note:

If you want to search a string for a particular pattern rather than a specific substring, you should use regular expressions. For more information, see .NET Framework Regular Expressions.

Modifying a string

The String class includes the following methods that appear to modify the value of a string:

Note:

All string modification methods return a new String object. They do not modify the value of the current instance.

Extracting substrings from a string

The String.Split(Char[]) method separates a single string into multiple strings. Overloads of the method allow you to specify multiple delimiters, to determine the maximum number of substrings that the method extracts, and to determine whether empty strings (which occur when delimiters are adjacent) are included among the returned strings.

Combining strings

The following String methods can be used for string concatenation:

Formatting values

The erload:System.String.Format method uses the composite formatting feature to replace one or more placeholders in a string with the string representation of some object or value. The erload:System.String.Format method is often used to do the following:

  • To embed the string representation of a numeric value in a string.

  • To embed the string representation of a date and time value in a string.

  • To embed the string representation of an enumeration value in a string.

  • To embed the string representation of some object that supports the IFormattable interface in a string.

  • To right-justify or left-justify a substring in a field within a larger string.

For detailed information about formatting operations and examples, see the erload:System.String.Format overload summary.

Copying a string

You can call the following String methods to make a copy of a string:

Normalizing a string

In Unicode, a single character can have multiple code points. Normalization converts these equivalent characters into the same binary representation. The String.Normalize method performs the normalization, and the String.IsNormalized method determines whether a string is normalized.

Thread Safety

This type is safe for multithreaded operations.

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, 4.0.0.0

The members of System.String are listed below.

See Also: Object

Public Constructors

Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters.

Initializes a new instance of the String class to the value indicated by an array of Unicode characters.

Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers.

Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.

Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length.

Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length.

Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length.

Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.

Public Fields

static readonly
EmptyString.

Represents the empty string. This field is read-only.

Public Properties

[read-only]
default property
Chars(Int32)Char. Gets the character at a specified position in the current instance.
[read-only]
LengthInt32.

Gets the number of characters in the current String object.

Public Methods

Clone() : Object

Returns a reference to this instance of String.

static
Compare(String, String) : Int32

Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

static
Compare(String, String, Boolean) : Int32

Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

static
Compare(String, String, StringComparison) : Int32

Compares two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

static
Compare(String, String, Boolean, CultureInfo) : Int32

Compares two specified String objects, ignoring or honoring their case, and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

static
Compare(String, String, CultureInfo, CompareOptions) : Int32

Compares two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two strings to each other in the sort order.

static
Compare(String, Int32, String, Int32, Int32) : Int32

Compares substrings of two specified String objects and returns an integer that indicates their relative position in the sort order.

static
Compare(String, Int32, String, Int32, Int32, Boolean) : Int32

Compares substrings of two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

static
Compare(String, Int32, String, Int32, Int32, StringComparison) : Int32

Compares substrings of two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

static
Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) : Int32

Compares substrings of two specified String objects, ignoring or honoring their case and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

static
Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) : Int32

Compares substrings of two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two substrings to each other in the sort order.

static
CompareOrdinal(String, String) : Int32

Compares two specified String objects by evaluating the numeric values of the corresponding Char objects in each string.

static
CompareOrdinal(String, Int32, String, Int32, Int32) : Int32

Compares substrings of two specified String objects by evaluating the numeric values of the corresponding Char objects in each substring.

CompareTo(Object) : Int32

Compares this instance with a specified Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.

CompareTo(String) : Int32

Compares this instance with a specified String object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified String.

static
Concat(IEnumerable<string>) : String

Concatenates the members of a constructed IEnumerable`1 collection of type String.

static
Concat(Object) : String

Creates the string representation of a specified object.

static
Concat(params Object[]) : String

Concatenates the string representations of the elements in a specified Object array.

static
Concat(params String[]) : String

Concatenates the elements of a specified String array.

static
Concat(Object, Object) : String

Concatenates the string representations of two specified objects.

static
Concat(String, String) : String

Concatenates two specified instances of String.

static
Concat(Object, Object, Object) : String

Concatenates the string representations of three specified objects.

static
Concat(String, String, String) : String

Concatenates three specified instances of String.

static
Concat(Object, Object, Object, Object) : String

Concatenates the string representations of four specified objects and any objects specified in an optional variable length parameter list.

static
Concat(String, String, String, String) : String

Concatenates four specified instances of String.

static
Concat<T>(IEnumerable<T>) : String

Concatenates the members of an IEnumerable`1 implementation.

Contains(String) : Boolean

Returns a value indicating whether a specified substring occurs within this string.

static
Copy(String) : String

Creates a new instance of String with the same value as a specified String.

CopyTo(Int32, Char[], Int32, Int32)

Copies a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.

EndsWith(String) : Boolean

Determines whether the end of this string instance matches the specified string.

EndsWith(String, StringComparison) : Boolean

Determines whether the end of this string instance matches the specified string when compared using the specified comparison option.

EndsWith(String, Boolean, CultureInfo) : Boolean

Determines whether the end of this string instance matches the specified string when compared using the specified culture.

override
Equals(Object) : Boolean

Determines whether this instance and a specified object, which must also be a String object, have the same value.

Equals(String) : Boolean

Determines whether this instance and another specified String object have the same value.

static
Equals(String, String) : Boolean

Determines whether two specified String objects have the same value.

Equals(String, StringComparison) : Boolean

Determines whether this string and a specified String object have the same value. A parameter specifies the culture, case, and sort rules used in the comparison.

static
Equals(String, String, StringComparison) : Boolean

Determines whether two specified String objects have the same value. A parameter specifies the culture, case, and sort rules used in the comparison.

static
Format(String, Object) : String

Replaces one or more format items in a specified string with the string representation of a specified object.

static
Format(String, params Object[]) : String

Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.

static
Format(IFormatProvider, String, params Object[]) : String

Replaces the format items in a specified string with the string representations of corresponding objects in a specified array. A parameter supplies culture-specific formatting information.

static
Format(String, Object, Object) : String

Replaces the format items in a specified string with the string representation of two specified objects.

static
Format(String, Object, Object, Object) : String

Replaces the format items in a specified string with the string representation of three specified objects.

GetEnumerator() : CharEnumerator

Retrieves an object that can iterate through the individual characters in this string.

override
GetHashCode() : Int32

Returns the hash code for this string.

GetTypeCode() : TypeCode

Returns the TypeCode for class String.

IndexOf(Char) : Int32

Reports the zero-based index of the first occurrence of the specified Unicode character in this string.

IndexOf(String) : Int32

Reports the zero-based index of the first occurrence of the specified string in this instance.

IndexOf(Char, Int32) : Int32

Reports the zero-based index of the first occurrence of the specified Unicode character in this string. The search starts at a specified character position.

IndexOf(String, Int32) : Int32

Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified character position.

IndexOf(String, StringComparison) : Int32

Reports the zero-based index of the first occurrence of the specified string in the current String object. A parameter specifies the type of search to use for the specified string.

IndexOf(Char, Int32, Int32) : Int32

Reports the zero-based index of the first occurrence of the specified character in this instance. The search starts at a specified character position and examines a specified number of character positions.

IndexOf(String, Int32, Int32) : Int32

Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified character position and examines a specified number of character positions.

IndexOf(String, Int32, StringComparison) : Int32

Reports the zero-based index of the first occurrence of the specified string in the current String object. Parameters specify the starting search position in the current string and the type of search to use for the specified string.

IndexOf(String, Int32, Int32, StringComparison) : Int32

Reports the zero-based index of the first occurrence of the specified string in the current String object. Parameters specify the starting search position in the current string, the number of characters in the current string to search, and the type of search to use for the specified string.

IndexOfAny(Char[]) : Int32

Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.

IndexOfAny(Char[], Int32) : Int32

Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. The search starts at a specified character position.

IndexOfAny(Char[], Int32, Int32) : Int32

Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. The search starts at a specified character position and examines a specified number of character positions.

Insert(Int32, String) : String

Returns a new string in which a specified string is inserted at a specified index position in this instance.

static
Intern(String) : String

Retrieves the system's reference to the specified String.

static
IsInterned(String) : String

Retrieves a reference to a specified String.

IsNormalized() : Boolean

Indicates whether this string is in Unicode normalization form C.

IsNormalized(NormalizationForm) : Boolean

Indicates whether this string is in the specified Unicode normalization form.

static
IsNullOrEmpty(String) : Boolean

Indicates whether the specified string is null or an String.Empty string.

static
IsNullOrWhiteSpace(String) : Boolean

Indicates whether a specified string is null, empty, or consists only of white-space characters.

static
Join(String, IEnumerable<string>) : String

Concatenates the members of a constructed IEnumerable`1 collection of type String, using the specified separator between each member.

static
Join(String, params Object[]) : String

Concatenates the elements of an object array, using the specified separator between each element.

static
Join(String, params String[]) : String

Concatenates all the elements of a string array, using the specified separator between each element.

static
Join(String, String[], Int32, Int32) : String

Concatenates the specified elements of a string array, using the specified separator between each element.

static
Join<T>(String, IEnumerable<T>) : String

Concatenates the members of a collection, using the specified separator between each member.

LastIndexOf(Char) : Int32

Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance.

LastIndexOf(String) : Int32

Reports the zero-based index position of the last occurrence of a specified string within this instance.

LastIndexOf(Char, Int32) : Int32

Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(String, Int32) : Int32

Reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(String, StringComparison) : Int32

Reports the zero-based index of the last occurrence of a specified string within the current String object. A parameter specifies the type of search to use for the specified string.

LastIndexOf(Char, Int32, Int32) : Int32

Reports the zero-based index position of the last occurrence of the specified Unicode character in a substring within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

LastIndexOf(String, Int32, Int32) : Int32

Reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

LastIndexOf(String, Int32, StringComparison) : Int32

Reports the zero-based index of the last occurrence of a specified string within the current String object. The search starts at a specified character position and proceeds backward toward the beginning of the string. A parameter specifies the type of comparison to perform when searching for the specified string.

LastIndexOf(String, Int32, Int32, StringComparison) : Int32

Reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string for the specified number of character positions. A parameter specifies the type of comparison to perform when searching for the specified string.

LastIndexOfAny(Char[]) : Int32

Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array.

LastIndexOfAny(Char[], Int32) : Int32

Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOfAny(Char[], Int32, Int32) : Int32

Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

Normalize() : String

Returns a new string whose textual value is the same as this string, but whose binary representation is in Unicode normalization form C.

Normalize(NormalizationForm) : String

Returns a new string whose textual value is the same as this string, but whose binary representation is in the specified Unicode normalization form.

PadLeft(Int32) : String

Returns a new string that right-aligns the characters in this instance by padding them with spaces on the left, for a specified total length.

PadLeft(Int32, Char) : String

Returns a new string that right-aligns the characters in this instance by padding them on the left with a specified Unicode character, for a specified total length.

PadRight(Int32) : String

Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.

PadRight(Int32, Char) : String

Returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length.

Remove(Int32) : String

Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.

Remove(Int32, Int32) : String

Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.

Replace(Char, Char) : String

Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.

Replace(String, String) : String

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

Split(params Char[]) : String[]

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array.

Split(Char[], Int32) : String[]

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array. A parameter specifies the maximum number of substrings to return.

Split(Char[], StringSplitOptions) : String[]

Returns a string array that contains the substrings in this string that are delimited by elements of a specified Unicode character array. A parameter specifies whether to return empty array elements.

Split(String[], StringSplitOptions) : String[]

Returns a string array that contains the substrings in this string that are delimited by elements of a specified string array. A parameter specifies whether to return empty array elements.

Split(Char[], Int32, StringSplitOptions) : String[]

Returns a string array that contains the substrings in this string that are delimited by elements of a specified Unicode character array. Parameters specify the maximum number of substrings to return and whether to return empty array elements.

Split(String[], Int32, StringSplitOptions) : String[]

Returns a string array that contains the substrings in this string that are delimited by elements of a specified string array. Parameters specify the maximum number of substrings to return and whether to return empty array elements.

StartsWith(String) : Boolean

Determines whether the beginning of this string instance matches the specified string.

StartsWith(String, StringComparison) : Boolean

Determines whether the beginning of this string instance matches the specified string when compared using the specified comparison option.

StartsWith(String, Boolean, CultureInfo) : Boolean

Determines whether the beginning of this string instance matches the specified string when compared using the specified culture.

Substring(Int32) : String

Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.

Substring(Int32, Int32) : String

Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

ToCharArray() : Char[]

Copies the characters in this instance to a Unicode character array.

ToCharArray(Int32, Int32) : Char[]

Copies the characters in a specified substring in this instance to a Unicode character array.

ToLower() : String

Returns a copy of this string converted to lowercase.

ToLower(CultureInfo) : String

Returns a copy of this string converted to lowercase, using the casing rules of the specified culture.

ToLowerInvariant() : String

Returns a copy of this String object converted to lowercase using the casing rules of the invariant culture.

override
ToString() : String

Returns this instance of String; no actual conversion is performed.

ToString(IFormatProvider) : String

Returns this instance of String; no actual conversion is performed.

ToUpper() : String

Returns a copy of this string converted to uppercase.

ToUpper(CultureInfo) : String

Returns a copy of this string converted to uppercase, using the casing rules of the specified culture.

ToUpperInvariant() : String

Returns a copy of this String object converted to uppercase using the casing rules of the invariant culture.

Trim() : String

Removes all leading and trailing white-space characters from the current String object.

Trim(params Char[]) : String

Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object.

TrimEnd(params Char[]) : String

Removes all trailing occurrences of a set of characters specified in an array from the current String object.

TrimStart(params Char[]) : String

Removes all leading occurrences of a set of characters specified in an array from the current String object.

Public Operators

static
Equality(String, String)

Determines whether two specified strings have the same value.

static
Inequality(String, String)

Determines whether two specified strings have different values.

Explicitly Implemented Interface Members

String$IEnumerable<Char>.GetEnumeratorThis method is implemented to support the System.Collections.Generics.IEnumerable<char> interface.
String$IEnumerable.GetEnumerator

Returns an enumerator that iterates through the current String object.

String$IConvertible.ToBoolean(IFormatProvider)

For a description of this member, see IConvertible.ToBoolean(IFormatProvider).

String$IConvertible.ToByte(IFormatProvider)

For a description of this member, see IConvertible.ToByte(IFormatProvider).

String$IConvertible.ToChar(IFormatProvider)

For a description of this member, see IConvertible.ToChar(IFormatProvider).

String$IConvertible.ToDateTime(IFormatProvider)

For a description of this member, see IConvertible.ToDateTime(IFormatProvider).

String$IConvertible.ToDecimal(IFormatProvider)

For a description of this member, see IConvertible.ToDecimal(IFormatProvider).

String$IConvertible.ToDouble(IFormatProvider)

For a description of this member, see IConvertible.ToDouble(IFormatProvider).

String$IConvertible.ToInt16(IFormatProvider)

For a description of this member, see IConvertible.ToInt16(IFormatProvider).

String$IConvertible.ToInt32(IFormatProvider)

For a description of this member, see IConvertible.ToInt32(IFormatProvider).

String$IConvertible.ToInt64(IFormatProvider)

For a description of this member, see IConvertible.ToInt64(IFormatProvider).

String$IConvertible.ToSByte(IFormatProvider)

For a description of this member, see IConvertible.ToSByte(IFormatProvider).

String$IConvertible.ToSingle(IFormatProvider)

For a description of this member, see IConvertible.ToSingle(IFormatProvider).

String$IConvertible.ToType(Type,IFormatProvider)

For a description of this member, see IConvertible.ToType(Type,IFormatProvider).

String$IConvertible.ToUInt16(IFormatProvider)

For a description of this member, see IConvertible.ToUInt16(IFormatProvider).

String$IConvertible.ToUInt32(IFormatProvider)

For a description of this member, see IConvertible.ToUInt32(IFormatProvider).

String$IConvertible.ToUInt64(IFormatProvider)

For a description of this member, see IConvertible.ToUInt64(IFormatProvider).