public sealed class String : ICloneable, IComparable, IEnumerable, IComparable<String>, IEquatable<String>, IEnumerable<Char>
Object
StringThis type implements IComparable, ICloneable, System.IComparable<System.String>, System.IEquatable<System.String>, IEnumerable, and System.Collections.Generic.IEnumerable<System.Char>.
mscorlib
BCL
Represents an immutable series of characters.
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 System.String.Length - 1.Strings are immutable; once created, the contents of a String do not change. Combining operations, such as System.String.Replace(System.Char,System.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 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 System.String.Copy(System.String) or the StringBuilder class.
To insert a formatted string representation of an object into a string, use the System.String.Format(System.String,System.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:
If an object referenced in the format string implements IFormattable, then the System.IFormattable.ToString(System.String,System.IFormatProvider) method of the object provides the formatting. If the argument does not implement IFormattable, then the System.Object.ToString method of the object provides default formatting, and formatSpecifier , if present, is ignored. For an example that demonstrates this, see Example 2.
- 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 System.IFormattable.ToString(System.String,System.IFormatProvider) format specifier. Therefore, all implementations of System.IFormattable.ToString(System.String,System.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 .
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 System.String.Format(System.String,System.Object) methods via System.Console.Write(System.String,System.Object) and System.Console.WriteLine. The primary difference is that the System.String.Format(System.String,System.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.
Example 1The following example demonstrates formatting numeric data types and inserting literal curly brackets into strings.
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
Some formatted numbers: dec= 1.999990E+000 doub= 1.0000000001 Literal curly brackets: {{ and }} and {{0}} A null argument looks like:Example 2The following example demonstrates how formatting works if IFormattable is or is not implemented by an argument to the System.String.Format(System.String,System.Object) method. Note that the format specifier is ignored if the argument does not implement IFormattable.
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
11 string 11 string [IFormattable called] 11 [IFormattable called] bExample 3The following example demonstrates searching for an empty string in a non-empty string.
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
0 2 3 5 1 4
DefaultMemberAttribute("Chars")
System Namespace
String Constructors
String(char, int) Constructor
String(char*) Constructor
String(char[]) Constructor
String(char*, int, int) Constructor
String(sbyte*, int, int, System.Text.Encoding) Constructor
String(char[], int, int) Constructor
String Methods
String.Clone Method
String.Compare(System.String, int, System.String, int, int, bool) Method
String.Compare(System.String, int, System.String, int, int) Method
String.Compare(System.String, System.String, bool) Method
String.Compare(System.String, System.String) Method
String.CompareOrdinal(System.String, System.String) Method
String.CompareOrdinal(System.String, int, System.String, int, int) Method
String.CompareTo(System.Object) Method
String.CompareTo(System.String) Method
String.Concat(System.Object, System.Object) Method
String.Concat(System.Object, System.Object, System.Object) Method
String.Concat(System.Object[]) Method
String.Concat(System.String, System.String) Method
String.Concat(System.String, System.String, System.String) Method
String.Concat(System.String[]) Method
String.Copy Method
String.CopyTo Method
String.EndsWith Method
String.Equals(System.Object) Method
String.Equals(System.String) Method
String.Equals(System.String, System.String) Method
String.Format(System.String, System.Object[]) Method
String.Format(System.String, System.Object) Method
String.Format(System.String, System.Object, System.Object) Method
String.Format(System.String, System.Object, System.Object, System.Object) Method
String.Format(System.IFormatProvider, System.String, System.Object[]) Method
String.GetEnumerator Method
String.GetHashCode Method
String.IndexOf(char) Method
String.IndexOf(char, int) Method
String.IndexOf(char, int, int) Method
String.IndexOf(System.String) Method
String.IndexOf(System.String, int) Method
String.IndexOf(System.String, int, int) Method
String.IndexOfAny(char[]) Method
String.IndexOfAny(char[], int) Method
String.IndexOfAny(char[], int, int) Method
String.Insert Method
String.Intern Method
String.IsInterned Method
String.Join(System.String, System.String[]) Method
String.Join(System.String, System.String[], int, int) Method
String.LastIndexOf(System.String, int) Method
String.LastIndexOf(System.String, int, int) Method
String.LastIndexOf(System.String) Method
String.LastIndexOf(char, int, int) Method
String.LastIndexOf(char, int) Method
String.LastIndexOf(char) Method
String.LastIndexOfAny(char[]) Method
String.LastIndexOfAny(char[], int) Method
String.LastIndexOfAny(char[], int, int) Method
String.PadLeft(int) Method
String.PadLeft(int, char) Method
String.PadRight(int, char) Method
String.PadRight(int) Method
String.Remove Method
String.Replace(System.String, System.String) Method
String.Replace(char, char) Method
String.Split(char[]) Method
String.Split(char[], int) Method
String.StartsWith Method
String.Substring(int, int) Method
String.Substring(int) Method
String.System.Collections.Generic.IEnumerable<System.Char>.GetEnumerator Method
String.System.Collections.IEnumerable.GetEnumerator Method
String.ToCharArray() Method
String.ToCharArray(int, int) Method
String.ToLower Method
String.ToString() Method
String.ToString(System.IFormatProvider) Method
String.ToUpper Method
String.Trim(char[]) Method
String.Trim() Method
String.TrimEnd Method
String.TrimStart Method
String.op_Equality Method
String.op_Inequality Method
String Fields
String Properties
public String(char c, int count);
Constructs and initializes a new instance of String .
- c
- A Char .
- count
- A Int32 containing the number of occurrences of c.
Exception Type Condition ArgumentOutOfRangeException count is less than zero.
If the specified number is 0, System.String.Empty is created.
The following example demonstrates using this constructor.
using System; public class StringExample { public static void Main() { string s = new String('a', 10); Console.WriteLine(s); } }The output is
aaaaaaaaaa
System.String Class, System Namespace
unsafe public String(char* value);
Constructs and initializes a new instance of String using a specified pointer to a sequence of Unicode characters.
- value
- A pointer to a null-terminated array of Unicode characters. If value is a null pointer, System.String.Empty is created.
This member is not CLS-compliant. For a CLS-compliant alternative, use the String(Char[] ) constructor.This constructor copies the sequence of Unicode characters at the specified pointer until a null character (hexadecimal 0x00) is reached.
If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation.
[Note: In C# this constructor is defined only in the context of unmanaged code.]
CLSCompliantAttribute(false)
System.String Class, System Namespace
public String(char[] value);
Constructs and initializes a new instance of String by copying the specified array of Unicode characters.
- value
- An array of Unicode characters.
If the specified array is a null reference or contains no elements, System.String.Empty is created.
System.String Class, System Namespace
unsafe public String(char* value, int startIndex, int length);
Constructs and initializes a new instance of String using a specified pointer to a sequence of Unicode characters, the index within that sequence at which to start copying characters, and the number of characters to be copied to construct the String .
- value
- A pointer to an array of Unicode characters.
- startIndex
- A Int32 containing the index within the array referenced by value from which to start copying.
- length
- A Int32 containing the number of characters to copy from value to the new String. If length is zero, System.String.Empty is created.
Exception Type Condition ArgumentOutOfRangeException startIndex or length is less than zero. -or-
value is a null pointer and length is not zero.
This member is not CLS-compliant. For a CLS-compliant alternative, use the String(Char, Int32, Int32) constructor.This constructor copies Unicode characters from value, starting at startIndex and ending at (startIndex + length - 1).
If the specified range is outside of the memory allocated for the sequence of characters, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation.
[Note: In C# this constructor is defined only in the context of unmanaged code.]
CLSCompliantAttribute(false)
System.String Class, System Namespace
unsafe public String(sbyte* value, int startIndex, int length, Encoding enc);
Constructs and initializes a new instance of theString
class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting character position within that array, a length, and anEncoding
object.
- value
- A pointer to a SByte array.
- startIndex
- A Int32 containing the starting position within value.
- length
- A Int32 containing the number of characters within value to use. If length is zero, System.String.Empty is created.
- enc
- A Encoding object that specifies how the array referenced by value is encoded.
Exception Type Condition ArgumentOutOfRangeException startIndex or length is less than zero. -or-
value is a null pointer and length is not zero.
If value is anull
pointer, a System.String.Empty instance is constructed.
CLSCompliantAttribute(false)
RuntimeInfrastructure
System.String Class, System Namespace
public String(char[] value, int startIndex, int length);
Constructs and initializes a new instance of String using an array of Unicode characters, the index within array at which to start copying characters, and the number of characters to be copied.
- value
- An array of Unicode characters.
- startIndex
- A Int32 containing the index within the array referenced by value from which to start copying.
- length
- A Int32 containing the number of characters to copy from the value array. If length is zero, System.String.Empty is created.
Exception Type Condition ArgumentNullException value is a null reference. ArgumentOutOfRangeException startIndex or length is less than zero. -or-
The sum of startIndex and length is greater than the number of elements in value .
This constructor copies the sequence Unicode characters found at value between indexes startIndex and startIndex + length - 1.
System.String Class, System Namespace
public object Clone();
Returns a reference to the current instance of String.
A reference to the current instance of String.
[Note: System.String.Clone does not generate a new String instance. Use the System.String.Copy(System.String) or System.String.CopyTo(System.Int32,System.Char[],System.Int32,System.Int32) method to create a separate String object with the same value as the current instance.This method is implemented to support the ICloneable interface.
]
System.String Class, System Namespace
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);
Compares substrings of two strings, ignoring or honoring their case.
- strA
- The first String containing a substring to compare. Can be a null reference.
- indexA
- A Int32 containing the starting index of the substring within strA.
- strB
- The second String containing a substring to compare. Can be a null reference.
- indexB
- A Int32 containing the starting index of the substring within strB.
- length
- A Int32 containing the maximum number of characters in the substrings to compare. If length is zero, then zero is returned.
- ignoreCase
- A Boolean indicating if the comparison is case-insensitive. If ignoreCase is
true
, the comparison is case-insensitive. If ignoreCase isfalse
, the comparison is case-sensitive, and uppercase letters evaluate greater than their lowercase equivalents.
The return value is a negative number, zero, or a positive number reflecting the sort order of the specified substrings. For non-zero return values, the exact value returned by this method is unspecified. The following table defines the return value:
Value Type Condition A negative number The substring in strA is < the substring in strB. Zero The substring in strA == the substring in strB, or length is zero. A positive number The substring in strA is > the substring in strB.
Exception Type Condition ArgumentOutOfRangeException indexA is greater than strA .Length -or-
indexB is greater than strB .Length
-or-
indexA, indexB, or length is negative.
[Note: The result of comparing any String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lower case equivalents.The maximum number of characters compared is the lesser of the length of strA less indexA, the length of strB less indexB, and length.
When a culture is available, the method uses the culture of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.
]
The following example demonstrates comparing substrings with and without case sensitivity.
using System; public class StringCompareExample { public static void Main() { string strA = "STRING A"; string strB = "string b"; int first = String.Compare( strA, strB, true ); int second = String.Compare( strA, 0, strB, 0, 4, true ); int third = String.Compare( strA, 0, strB, 0, 4, false ); Console.WriteLine( "When the string 'STRING A' is compared to the string 'string b' in a case-insensitive manner, the return value is {0}.", first ); Console.WriteLine( "When the substring 'STRI' of 'STRING A' is compared to the substring 'stri' of 'string b' in a case-insensitive manner, the return value is {0}.", second ); Console.WriteLine( "When the substring 'STRI' of 'STRING A' is compared to the substring 'stri' of 'string b' in a case-sensitive manner, the return value is {0}.", third ); } }The output is
When the string 'STRING A' is compared to the string 'string b' in a case-insensitive manner, the return value is -1.
When the substring 'STRI' of 'STRING A' is compared to the substring 'stri' of 'string b' in a case-insensitive manner, the return value is 0.
When the substring 'STRI' of 'STRING A' is compared to the substring 'stri' of 'string b' in a case-sensitive manner, the return value is 1.
System.String Class, System Namespace
public static int Compare(string strA, int indexA, string strB, int indexB, int length);
Compares substrings of two strings.
- strA
- The first String to compare. Can be a null reference.
- indexA
- A Int32 containing the starting index of the substring within strA.
- strB
- The second String to compare. Can be a null reference.
- indexB
- A Int32 containing the starting index of the substring within strB.
- length
- A Int32 containing the maximum number of characters in the substrings to compare. If length is zero, then zero is returned.
The return value is a negative number, zero, or a positive number reflecting the sort order of the specified substrings. For non-zero return values, the exact value returned by this method is unspecified. The following table defines the return value:
Value Meaning A negative number The substring in strA is < the substring in strB. Zero The substring in strA == the substring in strB, or length is zero. A positive number The substring in strA is > the substring in strB.
Exception Type Condition ArgumentOutOfRangeException The sum of indexA and length is greater than strA .Length . -or-
The sum of indexB and length is greater than strB .Length .
-or-
indexA, indexB, or length is negative.
[Note: The result of comparing any String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents.The method uses the culture (if any) of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.
]
The following example demonstrates comparing substrings.
using System; public class StringCompareExample { public static void Main() { string strA = "A string"; string strB = "B ring"; int first = String.Compare( strA, 4, strB, 2, 3 ); int second = String.Compare( strA, 3, strB, 3, 3 ); Console.WriteLine( "When the substring 'rin' of 'A string' is compared to the substring 'rin' of 'B ring', the return value is {0}.", first ); Console.WriteLine( "When the substring 'tri' of 'A string' is compared to the substring 'ing' of 'B ring', the return value is {0}.", second ); } }The output is
When the substring 'rin' of 'A string' is compared to the substring 'rin' of 'B ring', the return value is 0.
When the substring 'tri' of 'A string' is compared to the substring 'ing' of 'B ring', the return value is 1.
System.String Class, System Namespace
public static int Compare(string strA, string strB, bool ignoreCase);
Returns sort order of two String objects, ignoring or honoring their case.
- strA
- The first String to compare. Can be a null reference.
- strB
- The second String to compare. Can be a null reference.
- ignoreCase
- A Boolean indicating whether the comparison is case-insensitive. If ignoreCase is
true
, the comparison is case-insensitive. If ignoreCase isfalse
, the comparison is case-sensitive, and uppercase letters evaluate greater than their lowercase equivalents.
The return value is a negative number, zero, or a positive number reflecting the sort order of the specified substrings. For non-zero return values, the exact value returned by this method is unspecified. The following table defines the return value:
Value Meaning A negative number strA is < strB. Zero strA == strB. A positive number strA is > strB.
[Note: The result of comparing any String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents.The method uses the culture (if any) of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.
String.Compare
(strA, strB,false
) is equivalent toString.Compare
(strA, strB ).]
The following example demonstrates comparing strings with and without case sensitivity.
using System; public class StringCompareExample { public static void Main() { string strA = "A STRING"; string strB = "a string"; int first = String.Compare( strA, strB, true ); int second = String.Compare( strA, strB, false ); Console.WriteLine( "When 'A STRING' is compared to 'a string' in a case-insensitive manner, the return value is {0}.", first ); Console.WriteLine( "When 'A STRING' is compared to 'a string' in a case-sensitive manner, the return value is {0}.", second ); } }The output is
When 'A STRING' is compared to 'a string' in a case-insensitive manner, the return value is 0.
When 'A STRING' is compared to 'a string' in a case-sensitive manner, the return value is 1.
System.String Class, System Namespace
public static int Compare(string strA, string strB);
Compares two String objects in a case-sensitive manner.
- strA
- The first String to compare. Can be a null reference.
- strB
- The second String to compare. Can be a null reference.
The return value is a negative number, zero, or a positive number reflecting the sort order of the specified strings. For non-zero return values, the exact value returned by this method is unspecified. The following table defines the return value:
Value Meaning A negative number strA is lexicographically < strB. Zero strA is lexicographically == strB. A positive number strA is lexicographically > strB.
This method performs a case-sensitive operation.[Note: The result of comparing any String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents.
The method uses the culture (if any) of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.
]
System.String Class, System Namespace
public static int CompareOrdinal(string strA, string strB);
Compares two specified String objects based on the code points of the contained Unicode characters.
- strA
- The first String to compare.
- strB
- The second String to compare.
The return value is a negative number, zero, or a positive number reflecting the sort order of the specified strings. For non-zero return values, the exact value returned by this method is unspecified. The following table defines the return value:
Value Description A negative number strA is < strB, or strA is a null reference. Zero strA == strB, or both strA and strB are null references. A positive number strA is > strB, or strB is a null reference.
[Note: The result of comparing any String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents.The method uses the culture (if any) of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.
]
System.String Class, System Namespace
public static int CompareOrdinal(string strA, int indexA, string strB, int indexB, int length);
Compares substrings of two specified String objects based on the code points of the contained Unicode characters.
- strA
- The first String to compare.
- indexA
- A Int32 containing the starting index of the substring in strA.
- strB
- The second String to compare.
- indexB
- A Int32 containing the starting index of the substring in strB.
- length
- A Int32 containing the number of characters in the substrings to compare.
The return value is a negative number, zero, or a positive number reflecting the sort order of the specified strings. For non-zero return values, the exact value returned by this method is unspecified. The following table defines the return value:
Value Type Condition A negative number The substring in strA is < the substring in strB, or strA is a null reference. Zero The substring in strA == the substring in strB, or both strA and strB are null references. A positive number The substring in strA is > the substring in strB, or strB is a null reference.
Exception Type Condition ArgumentOutOfRangeException indexA is greater than strA .Length -or-
indexB is greater than strB .Length
-or-
indexA, indexB, or lengthis negative.
When either of the String arguments is the null reference an ArgumentOutOfRangeException shall be thrown if the corresponding index is non-zero.[Note: The maximum number of characters compared is the lesser of the length of strA less indexA, the length of strB less indexB, and length.
The result of comparing any String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Upper case letters evaluate greater than their lowercase equivalents.
The method uses the culture (if any) of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.
]
System.String Class, System Namespace
public int CompareTo(object value);
Returns the sort order of the current instance compared to the specified object.
- value
- The Object to compare to the current instance.
The return value is a negative number, zero, or a positive number reflecting the sort order of the current instance as compared to value. For non-zero return values, the exact value returned by this method is unspecified. The following table defines the return value:
Value Condition A negative number The current instance is lexicographically < value. Zero The current instance is lexicographically == value. A positive number
The current instance is lexicographically > value, or value is a null reference.
Exception Type Condition ArgumentException value is not a String.
value is required to be a String object.[Note: The result of comparing any String (including the empty string) to a null reference is greater than zero. Uppercase letters evaluate greater than their lowercase equivalents.
The method uses the culture (if any) of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.
This method is implemented to support the IComparable interface.
]
System.String Class, System Namespace
public int CompareTo(string strB);
Returns the sort order of the current instance compared to the specified string.
- strB
- The String to compare to the current instance.
The return value is a negative number, zero, or a positive number reflecting the sort order of the current instance as compared to strB. For non-zero return values, the exact value returned by this method is unspecified. The following table defines the return value:
Value Condition A negative number The current instance is lexicographically < strB. Zero The current instance is lexicographically == strB. A positive number
The current instance is lexicographically > strB, or strB is a null reference.
[Note: Uppercase letters evaluate greater than their lowercase equivalents.The method uses the culture (if any) of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.
This method is implemented to support the System.IComparable<System.String> interface.
]
System.String Class, System Namespace
public static string Concat(object arg0, object arg1);
Concatenates the String representations of two specified objects.
- arg0
- The first Object to concatenate.
- arg1
- The second Object to concatenate.
The concatenated String representation of the values of arg0 and arg1.
System.String.Empty is used in place of any null argument.This version of System.String.Concat(System.Object) is equivalent to System.String.Concat(System.Object)( arg0.ToString(), arg1.ToString () ).
[Note: If either of the arguments is an array reference, the method concatenates a string representing that array, instead of its members (for example, String )[].]
The following example demonstrates concatenating two objects.
using System; public class StringConcatExample { public static void Main() { string str = String.Concat( 'c', 32 ); Console.WriteLine( "The concatenated Objects are: {0}", str ); } }The output is
The concatenated Objects are: c32
System.String Class, System Namespace
public static string Concat(object arg0, object arg1, object arg2);
Concatenates the String representations of three specified objects, in order provided.
- arg0
- The first Object to concatenate.
- arg1
- The second Object to concatenate.
- arg2
- The third Object to concatenate.
The concatenated String representations of the values of arg0, arg1, and arg2.
This method concatenates the values returned by the System.String.ToString methods on every argument. System.String.Empty is used in place of any null argument.This version of System.String.Concat(System.Object) is equivalent to
String.Concat
( arg0.ToString
(), arg1.ToString
(), arg2.ToString
() ).
The following example demonstrates concatenating three objects.
using System; public class StringConcatExample { public static void Main() { string str = String.Concat( 'c', 32, "String" ); Console.WriteLine( "The concatenated Objects are: {0}", str ); } }The output is
The concatenated Objects are: c32String
System.String Class, System Namespace
public static string Concat(params object[] args);
Concatenates the String representations of the elements in an array of Object instances.
- args
- An array of Object instances to concatenate.
The concatenated String representations of the values of the elements in args.
Exception Type Condition ArgumentNullException args is a null reference.
This method concatenates the values returned by the System.String.ToString methods on every object in the args array. System.String.Empty is used in place of any null reference in the array.
The following example demonstrates concatenating an array of objects.
using System; public class StringConcatExample { public static void Main() { string str = String.Concat( 'c', 32, "String" ); Console.WriteLine( "The concatenated Object array is: {0}", str ); } }The output is
The concatenated Object array is: c32String
System.String Class, System Namespace
public static string Concat(string str0, string str1);
Concatenates two specified instances of String.
- str0
- The first String to concatenate.
- str1
- The second String to concatenate.
A String containing the concatenation of str0 and str1.
System.String.Empty is used in place of any null argument.
The following example demonstrates concatenating two strings.
using System; public class StringConcatExample { public static void Main() { string str = String.Concat( "one", "two" ); Console.WriteLine( "The concatenated strings are: {0}", str ); } }The output is
The concatenated strings are: onetwo
System.String Class, System Namespace
public static string Concat(string str0, string str1, string str2);
Concatenates three specified instances of String.
- str0
- The first String to concatenate.
- str1
- The second String to concatenate.
- str2
- The third String to concatenate.
A String containing the concatenation of str0, str1, and str2.
System.String.Empty is used in place of any null argument.
The following example demonstrates concatenating three strings.
using System; public class StringConcatExample { public static void Main() { string str = String.Concat( "one", "two", "three" ); Console.WriteLine( "The concatenated strings are: {0}", str ); } }The output is
The concatenated strings are: onetwothree
System.String Class, System Namespace
public static string Concat(params string[] values);
Concatenates the elements of a specified array.
- values
- An array of String instances to concatenate.
A String containing the concatenated elements of values.
Exception Type Condition ArgumentNullException values is a null reference.
System.String.Empty is used in place of any null reference in the array.
The following example demonstrates concatenating an array of strings.
using System; public class StringConcatExample { public static void Main() { string str = String.Concat( "one", "two", "three", "four", "five" ); Console.WriteLine( "The concatenated String array is: {0}", str ); } }The output is
The concatenated String array is: onetwothreefourfive
System.String Class, System Namespace
public static string Copy(string str);
Creates a new instance of String with the same value as a specified instance of String.
- str
- The String to be copied.
A new String with the same value as str.
Exception Type Condition ArgumentNullException str is a null reference.
The following example demonstrates copying strings.
using System; public class StringCopyExample { public static void Main() { string strA = "string"; Console.WriteLine( "The initial string, strA, is '{0}'.", strA ); string strB = String.Copy( strA ); strA = strA.ToUpper(); Console.WriteLine( "The copied string, strB, before strA.ToUpper, is '{0}'.", strB ); Console.WriteLine( "The initial string after StringCopy and ToUpper, is '{0}'.", strA ); Console.WriteLine( "The copied string, strB, after strA.ToUpper, is '{0}'.", strB ); } }The output is
The initial string, strA, is 'string'.
The copied string, strB, before strA.ToUpper, is 'string'.
The initial string after StringCopy and ToUpper, is 'STRING'.
The copied string, strB, after strA.ToUpper, is 'string'.
System.String Class, System Namespace
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
Copies a specified number of characters from a specified position in the current String instance to a specified position in a specified array of Unicode characters.
- sourceIndex
- A Int32 containing the index of the current instance from which to copy.
- destination
- An array of Unicode characters.
- destinationIndex
- A Int32 containing the index of an array element in destination to copy.
- count
- A Int32 containing the number of characters in the current instance to copy to destination.
Exception Type Condition ArgumentNullException destination is a null reference. ArgumentOutOfRangeException sourceIndex, destinationIndex, or count is negative -or-
count is greater than the length of the substring from startIndex to the end of the current instance
-or-
count is greater than the length of the subarray from destinationIndex to the end of destination
The following example demonstrates copying characters from a string to a Unicode character array.
using System; public class StringCopyToExample { public static void Main() { string str = "this is the new string"; Char[] cAry = {'t','h','e',' ','o','l','d'}; Console.WriteLine( "The initial string is '{0}'", str ); Console.Write( "The initial character array is: '" ); foreach( Char c in cAry) Console.Write( c ); Console.WriteLine( "'" ); str.CopyTo( 12, cAry, 4, 3 ); Console.Write( "The character array after CopyTo is: '" ); foreach( Char c in cAry) Console.Write( c ); Console.WriteLine("'"); } }The output is
The initial string is 'this is the new string'
The initial character array is: 'the old'
The character array after CopyTo is: 'the new'
System.String Class, System Namespace
public bool EndsWith(string value);
Returns a Boolean value that indicates whether the ending characters of the current instance match the specified String.
- value
- A String to match.
true
if the end of the current instance is equal to value;false
if value is not equal to the end of the current instance or is longer than the current instance.
Exception Type Condition ArgumentNullException value is a null reference.
This method compares value with the substring at the end of the current instance that has a same length as value.The comparison is case-sensitive.
The following example demonstrates determining whether the current instance ends with a specified string.
using System; public class StringEndsWithExample { public static void Main() { string str = "One string to compare"; Console.WriteLine( "The given string is '{0}'", str ); Console.Write( "The given string ends with 'compare'? " ); Console.WriteLine( str.EndsWith( "compare" ) ); Console.Write( "The given string ends with 'Compare'? " ); Console.WriteLine( str.EndsWith( "Compare" ) ); } }The output is
The given string is 'One string to compare'
The given string ends with 'compare'? True
The given string ends with 'Compare'? False
System.String Class, System Namespace
public override bool Equals(object obj);
Determines whether the current instance and the specified object have the same value.
- obj
- A Object.
true
if obj is a String and its value is the same as the value of the current instance; otherwise,false
.
Exception Type Condition NullReferenceException The current instance is a null reference.
This method checks for value equality. This comparison is case-sensitive.[Note: This method overrides System.Object.Equals(System.Object) .]
The following example demonstrates checking to see if an object is equal to the current instance.
using System; public class StringEqualsExample { public static void Main() { string str = "A string"; Console.WriteLine( "The given string is '{0}'", str ); Console.Write( "The given string is equal to 'A string'? " ); Console.WriteLine( str.Equals( "A string" ) ); Console.Write( "The given string is equal to 'A String'? " ); Console.WriteLine( str.Equals( "A String" ) ); } }The output is
The given string is 'A string'
The given string is equal to 'A string'? True
The given string is equal to 'A String'? False
System.String Class, System Namespace
public override bool Equals(string value);
Determines whether the current instance and the specified string have the same value.
- value
- A String.
true
if the value of value is the same as the value of the current instance; otherwise,false
.
This method checks for value equality. This comparison is case-sensitive.[Note: This method is implemented to support the System.IEquatable<System.String> interface.]
System.String Class, System Namespace
public static bool Equals(string a, string b);
Determines whether two specified String objects have the same value.
- a
- A String or a null reference.
- b
- A String or a null reference.
true
if the value of a is the same as the value of b; otherwise,false
.
The comparison is case-sensitive.
The following example demonstrates checking to see if two strings are equal.
using System; public class StringEqualsExample { public static void Main() { string strA = "A string"; string strB = "a string"; string strC = "a string"; Console.Write( "The string '{0}' is equal to the string '{1}'? ", strA, strB ); Console.WriteLine( String.Equals( strA, strB ) ); Console.Write( "The string '{0}' is equal to the string '{1}'? ", strC, strB ); Console.WriteLine( String.Equals( strC, strB ) ); } }The output is
The string 'A string' is equal to the string 'a string'? False
The string 'a string' is equal to the string 'a string'? True
System.String Class, System Namespace
public static string Format(string format, params object[] args);
Replaces the format specification in a specified String with the textual equivalent of the value of a corresponding Object instance in a specified array.
- format
- A String containing zero or more format specifications.
- args
- A Object array containing the objects to be formatted.
A String containing a copy of format in which the format specifications have been replaced by the String equivalent of the corresponding instances of Object in args.
Exception Type Condition ArgumentNullException format or args is a null reference. FormatException format is invalid. -or-
The number indicating an argument to be formatted is less than zero, or greater than or equal to the length of the args array.
If an object referenced in the format string is a null reference, an empty string is used in its place.[Note: This version of System.String.Format(System.String,System.Object) is equivalent to System.String.Format(System.String,System.Object)( null, format, args ). For more information on the format specification see the String class overview.]
The following example demonstrates the System.String.Format(System.String,System.Object) method.
using System; public class StringFormat { public static void Main() { Console.WriteLine( String.Format("The winning numbers were {0:000} {1:000} {2:000} {3:000} {4:000} today.", 5, 10, 11, 37, 42) ); Console.WriteLine( "The winning numbers were {0, -6}{1, -6}{2, -6}{3, -6}{4, -6} today.", 5, 10, 11, 37, 42 ); } }The output is
The winning numbers were 005 010 011 037 042 today. The winning numbers were 5 10 11 37 42 today.
System.String Class, System Namespace
public static string Format(string format, object arg0);
Replaces the format specification in a provided String with a specified textual equivalent of the value of a specified Object instance.
- format
- A String containing zero or more format specifications.
- arg0
- A Object to be formatted. Can be a null reference.
A copy of format in which the first format specification has been replaced by the formatted String equivalent of the arg0.
Exception Type Condition ArgumentNullException format is a null reference. FormatException The format specification in format is invalid. -or-
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (1).
If an object referenced in the format string is a null reference, an empty string is used in its place.[Note: This version of System.String.Format(System.String,System.Object) is equivalent to
String.Format
(null
, format,new Object
[] {arg0} ). For more information on the format specification see the String class overview.]
The following example demonstrates the System.String.Format(System.String,System.Object) method.
using System; public class StringFormat { public static void Main() { Console.WriteLine(String.Format("The high temperature today was {0:###} degrees.", 88)); Console.WriteLine("The museum had {0,-6} visitors today.", 88); } }The output is
The high temperature today was 88 degrees. The museum had 88 visitors today.
System.String Class, System Namespace
public static string Format(string format, object arg0, object arg1);
Replaces the format specification in a specified String with the textual equivalent of the value of two specified Object instances.
- format
- A String containing zero or more format specifications.
- arg0
- A Object to be formatted. Can be a null reference.
- arg1
- A Object to be formatted. Can be a null reference.
A String containing a copy of format in which the format specifications have been replaced by the String equivalent of arg0 and arg1.
Exception Type Condition ArgumentNullException format is a null reference. FormatException format is invalid. -or-
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (2).
If an object referenced in the format string is a null reference, an empty string is used in its place.[Note: This version of System.String.Format(System.String,System.Object) is equivalent to
String.Format
(null
, format,new Object[]
{arg0, arg1} ). For more information on the format specification see the String class overview.]
The following example demonstrates the System.String.Format(System.String,System.Object) method.
using System; public class StringFormat { public static void Main() { Console.WriteLine( String.Format("The temperature today oscillated between {0:####} and {1:####} degrees.", 78, 100) ); Console.WriteLine( String.Format("The temperature today oscillated between {0:0000} and {1:0000} degrees.", 78, 100) ); Console.WriteLine( "The temperature today oscillated between {0, -4} and {1, -4} degrees.", 78, 100 ); } }The output is
The temperature today oscillated between 78 and 100 degrees. The temperature today oscillated between 0078 and 0100 degrees. The temperature today oscillated between 78 and 100 degrees.
System.String Class, System Namespace
public static string Format(string format, object arg0, object arg1, object arg2);
Replaces the format specification in a specified String with the textual equivalent of the value of three specified Object instances.
- format
- A String containing zero or more format specifications.
- arg0
- The first Object to be formatted. Can be a null reference.
- arg1
- The second Object to be formatted. Can be a null reference.
- arg2
- The third Object to be formatted. Can be a null reference.
A String containing a copy of format in which the first, second, and third format specifications have been replaced by the String equivalent of arg0, arg1, and arg2.
Exception Type Condition ArgumentNullException format is a null reference. FormatException format is invalid. -or-
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (3).
If an object referenced in the format string is a null reference, an empty string is used in its place.[Note: This version of System.String.Format(System.String,System.Object) is equivalent to
String.Format
(null
, format,new Object[]
{arg0, arg1, arg2} ). For more information on the format specification see the String class overview.]
The following example demonstrates the System.String.Format(System.String,System.Object) method.
using System; public class StringFormat { public static void Main() { Console.WriteLine(String.Format("The temperature today oscillated between {0:###} and {1:###} degrees. The average temperature was {2:000} degrees.", 78, 100, 91)); Console.WriteLine("The temperature today oscillated between {0, 4} and {1, 4} degrees. The average temperature was {2, 4} degrees.", 78, 100, 91); } }The output is
The temperature today oscillated between 78 and 100 degrees. The average temperature was 091 degrees. The temperature today oscillated between 78 and 100 degrees. The average temperature was 91 degrees.
System.String Class, System Namespace
public static string Format(IFormatProvider provider, string format, params object[] args);
Replaces the format specification in a specified String with the culture-specific textual equivalent of the value of a corresponding Object instance in a specified array.
- provider
- A IFormatProvider interface that supplies an object that provides culture-specific formatting information. Can be a null reference.
- format
- A String containing zero or more format specifications.
- args
- A Object array to be formatted.
A String containing a copy of format in which the format specifications have been replaced by the String equivalent of the corresponding instances of Object in args .
Exception Type Condition ArgumentNullException format or args is a null reference. FormatException format is invalid. -or-
The number indicating an argument to be formatted (N) is less than zero, or greater than or equal to the length of the args array.
If an object referenced in the format string is a null reference, an empty string is used in its place.The format parameter string is embedded with zero or more format specifications of the form, {N [, M ][: formatString ]}, where N is a zero-based integer indicating the argument to be formatted, M is an optional integer indicating the width of the region to contain the formatted value, and formatString is an optional string of formatting codes. [Note: For more information on the format specification see the String class overview.]
System.String Class, System Namespace
public CharEnumerator GetEnumerator();
Retrieves an object that can iterate through the individual characters in the current instance.
A CharEnumerator object.
This method is required by programming languages that support the IEnumerator interface to iterate through members of a collection.
System.String Class, System Namespace
public override int GetHashCode();
Generates a hash code for the current instance.
A Int32 containing the hash code for this instance.
The algorithm used to generate the hash code is unspecified.[Note: This method overrides System.Object.GetHashCode.]
System.String Class, System Namespace
public int IndexOf(char value);
Returns the index of the first occurrence of a specified Unicode character in the current instance.
- value
- A Unicode character.
A Int32 containing the zero-based index of the first occurrence of value character in the current instance; otherwise, -1 if value was not found.
This method is case-sensitive.
System.String Class, System Namespace
public int IndexOf(char value, int startIndex);
Returns the index of the first occurrence of a specified Unicode character in the current instance, with the search starting from a specified index.
- value
- A Unicode character.
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
A Int32 containing the zero-based index of the first occurrence of value in the current instance starting from the specified index; otherwise, -1 if value was not found.
Exception Type Condition ArgumentOutOfRangeException startIndex is less than zero or greater than the length of the current instance.
This method is case-sensitive.
The following example demonstrates the System.String.IndexOf(System.Char) method.
using System; public class StringIndexOf { public static void Main() { String str = "This is the string"; Console.WriteLine( "Searching for the index of 'h' starting from index 0 yields {0}.", str.IndexOf( 'h', 0 ) ); Console.WriteLine( "Searching for the index of 'h' starting from index 10 yields {0}.", str.IndexOf( 'h', 10 ) ); } }The output is
Searching for the index of 'h' starting from index 0 yields 1.
Searching for the index of 'h' starting from index 10 yields -1.
System.String Class, System Namespace
public int IndexOf(char value, int startIndex, int count);
Returns the index of the first occurrence of a specified Unicode character in the current instance, with the search over the specified range starting at the provided index.
- value
- A Unicode character.
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
- count
- A Int32 containing the number of consecutive elements of the current instance to be searched starting at startIndex.
A Int32 containing the zero-based index of the first occurrence of value in the current instance in the specified range of indexes; otherwise, -1 if value was not found.
Exception Type Condition ArgumentOutOfRangeException startIndex or count is negative -or-
startIndex + count is greater than the length of the current instance.
The search begins at startIndex and continues until startIndex + count - 1 is reached. The character at startIndex + count is not included in the search.This method is case-sensitive.
System.String Class, System Namespace
public int IndexOf(string value);
Returns the index of the first occurrence of a specified String in the current instance.
- value
- The String for which to search.
A Int32 that indicates the result of the search for value in the current instance as follows:
Return Value Description A zero-based number equal to the index of the start of the first substring in the current instance that is equal to value . value was found starting at the index returned. -1 value was not found.
Exception Type Condition ArgumentNullException value is a null reference.
The search begins at the first character of the current instance. The search is case-sensitive, culture-sensitive, and the culture (if any) of the current thread is used.
The following example demonstrates the System.String.IndexOf(System.Char) method.
using System; public class StringIndexOf { public static void Main() { String str = "This is the string"; Console.WriteLine( "Searching for the index of \"is\" yields {0,2}.", str.IndexOf( "is" ) ); Console.WriteLine( "Searching for the index of \"Is\" yields {0,2}.", str.IndexOf( "Is" ) ); Console.WriteLine( "Searching for the index of \"\" yields {0,2}.", str.IndexOf( "" ) ); } }The output is
Searching for the index of "is" yields 2.
Searching for the index of "Is" yields -1.
Searching for the index of "" yields 0.
System.String Class, System Namespace
public int IndexOf(string value, int startIndex);
Returns the index of the first occurrence of a specified String in the current instance, with the search starting from a specified index.
- value
- The String for which to search.
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
A Int32 that indicates the result of the search for value in the current instance as follows:
Return Value Description A zero-based number equal to the index of the start of the first substring in the current instance that is equal to value . value was found starting at the index returned. -1 value was not found.
Exception Type Condition ArgumentNullException value is a null reference. ArgumentOutOfRangeException startIndex is greater than the length of the current instance.
This method is case-sensitive.
System.String Class, System Namespace
public int IndexOf(string value, int startIndex, int count);
Returns the index of the first occurrence of a specified String in the current instance, with the search over the specified range starting at the provided index.
- value
- The String for which to search
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
- count
- A Int32 containing the number of consecutive elements of the current instance to be searched starting at startIndex.
A Int32 that indicates the result of the search for value in the current instance as follows:
Return Value Description A zero-based number equal to the index of the start of the first substring in the current instance that is equal to value . value was found starting at the index returned. -1 value was not found.
Exception Type Condition ArgumentNullException value is a null reference. ArgumentOutOfRangeException startIndex or count is negative -or-
startIndex + count is greater than the length of the current instance.
The search begins at startIndex and continues until startIndex + count - 1 is reached. The character at startIndex + count is not included in the search.This method is case-sensitive.
System.String Class, System Namespace
public int IndexOfAny(char[] anyOf);
Reports the index of the first occurrence in the current instance of any character in a specified array of Unicode characters.
- anyOf
- An array of Unicode characters.
The index of the first occurrence of an element of anyOf in the current instance; otherwise, -1 if no element of anyOf was found.
Exception Type Condition ArgumentNullException anyOf is a null reference.
This method is case-sensitive.
System.String Class, System Namespace
public int IndexOfAny(char[] anyOf, int startIndex);
Returns the index of the first occurrence of any element in a specified array of Unicode characters in the current instance, with the search starting from a specified index.
- anyOf
- An array of Unicode characters.
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
A Int32 containing a positive value equal to the index of the first occurrence of an element of anyOf in the current instance; otherwise, -1 if no element of anyOf was found.
Exception Type Condition ArgumentNullException anyOf is a null reference. ArgumentOutOfRangeException startIndex is greater than the length of the current instance
This method is case-sensitive.
System.String Class, System Namespace
public int IndexOfAny(char[] anyOf, int startIndex, int count);
Returns the index of the first occurrence of any element in a specified Array of Unicode characters in the current instance, with the search over the specified range starting from the provided index.
- anyOf
- An array containing the Unicode characters to seek.
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
- count
- A Int32 containing the range of the current instance at which to end searching.
A Int32 containing a positive value equal to the index of the first occurrence of an element of anyOf in the current instance; otherwise, -1 if no element of anyOf was found.
Exception Type Condition ArgumentNullException anyOf is a null reference. ArgumentOutOfRangeException startIndex or count is negative. -or-
startIndex + count is greater than the length of the current instance.
The search begins at startIndex and continues until startIndex + count - 1. The character at startIndex + count is not included in the search.This method is case-sensitive.
System.String Class, System Namespace
public string Insert(int startIndex, string value);
Returns a String equivalent to the current instance with a specified String inserted at the specified position.
- startIndex
- A Int32 containing the index of the insertion.
- value
- The String to insert.
A new String that is equivalent to the current string with value inserted at index startIndex.
Exception Type Condition ArgumentNullException value is a null reference. ArgumentOutOfRangeException startIndex is greater than the length of the current instance.
In the new string returned by this method, the first character of value is at startIndex, and all characters in the current string from startIndex to the end are inserted in the new string after the last character of value.
System.String Class, System Namespace
public static string Intern(string str);
Retrieves the system's reference to a specified String.
- str
- A String.
The String reference to str.
Exception Type Condition ArgumentNullException str is a null reference.
Instances of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically are kept in a table, called the "intern pool".The intern pool conserves string storage. If a literal string constant is assigned to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.
This method looks up a specified string in the intern pool. If the string exists, a reference to it is returned. If it does not exist, an instance equal to the specified string is added to the intern pool and a reference that instance is returned.
The following example demonstrates the System.String.Intern(System.String) method.
using System; using System.Text; public class StringExample { public static void Main() { String s1 = "MyTest"; String s2 = new StringBuilder().Append("My").Append("Test").ToString(); String s3 = String.Intern(s2); Console.WriteLine(Object.ReferenceEquals(s1, s2)); //different Console.WriteLine(Object.ReferenceEquals(s1, s3)); //the same } }The output is
False
True
System.String Class, System Namespace
public static string IsInterned(string str);
Retrieves a reference to a specified String.
- str
- A String.
A String reference to str if it is in the system's intern pool; otherwise, a null reference.
Exception Type Condition ArgumentNullException str is a null reference.
Instances of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically are kept in a table, called the "intern pool".The intern pool conserves string storage. If a literal string constant is assigned to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.
[Note: This method does not return a Boolean value, but can still be used where a Boolean is needed.]
The following example demonstrates the System.String.IsInterned(System.String) method.
using System; using System.Text; public class StringExample { public static void Main() { String s1 = new StringBuilder().Append("My").Append("Test").ToString(); Console.WriteLine(String.IsInterned(s1) != null); } }The output is
True
System.String Class, System Namespace
public static string Join(string separator, string[] value);
Concatenates the elements of a specified String array, inserting a separator string between each element pair and yielding a single concatenated string.
- separator
- A String.
- value
- A String array.
A String consisting of the elements of value separated by instances of the separator string.
Exception Type Condition ArgumentNullException value is a null reference.
The following example demonstrates the System.String.Join(System.String,System.String[]) method.
using System; public class StringJoin { public static void Main() { String[] strAry = { "Red" , "Green" , "Blue" }; Console.WriteLine( String.Join( " :: ", strAry ) ); } }The output is
Red :: Green :: Blue
System.String Class, System Namespace
public static string Join(string separator, string[] value, int startIndex, int count);
Concatenates a specified separator String between the elements of a specified String array, yielding a single concatenated string.
- separator
- A String.
- value
- A String array.
- startIndex
- A Int32 containing the first array element in value to join.
- count
- A Int32 containing the number of elements in value to join.
A String consisting of the specified strings in value joined by separator. Returns System.String.Empty if count is zero, value has no elements, or separator and all the elements of value areEmpty
.
Exception Type Condition ArgumentOutOfRangeException startIndex plus count is greater than the number of elements in value.
The following example demonstrates the System.String.Join(System.String,System.String[]) method.
using System; public class StringJoin { public static void Main() { String[] strAry = { "Red" , "Green" , "Blue" }; Console.WriteLine( String.Join( " :: ", strAry, 1, 2 ) ); } }The output is
Green :: Blue
System.String Class, System Namespace
public int LastIndexOf(string value, int startIndex);
Returns the index of the last occurrence of a specified String within the current instance, starting at a given position.
- value
- A String .
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
A Int32 that indicates the result of the search for value in the current instance as follows:
Return Value Description A zero-based number equal to the index of the start of the last substring in the current instance that is equal to value . value was found. -1 value was not found.
Exception Type Condition ArgumentNullException value is a null reference. ArgumentOutOfRangeException startIndex is less than zero or greater than or equal to the length of the current instance.
This method searches for the last occurrence of the specified String between the start of the string and the indicated index.This method is case-sensitive.
System.String Class, System Namespace
public int LastIndexOf(string value, int startIndex, int count);
Returns the index of the last occurrence of a specified String in the provided range of the current instance.
- value
- The substring to search for.
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
- count
- A Int32 containing the range of the current instance at which to end searching.
A Int32 that indicates the result of the search for value in the current instance as follows:
Return Value Description A zero-based number equal to the index of the start of the last substring in the current instance that is equal to value . value was found. -1 value was not found.
Exception Type Condition ArgumentNullException value is a null reference. ArgumentOutOfRangeException startIndex or count is less than zero. -or-
startIndex - count is smaller than -1.
The search begins at startIndex and continues until startIndex - count + 1.This method is case-sensitive.
System.String Class, System Namespace
public int LastIndexOf(string value);
Returns the index of the last occurrence of a specified String within the current instance.
- value
- A String .
A Int32 that indicates the result of the search for value in the current instance as follows:
Return Value Description A zero-based number equal to the index of the start of the last substring in the current instance that is equal to value . value was found. -1 value was not found.
Exception Type Condition ArgumentNullException value is a null reference.
The search is case-sensitive.
System.String Class, System Namespace
public int LastIndexOf(char value, int startIndex, int count);
Returns the index of the last occurrence of a specified character in the provided range of the current instance.
- value
- A Unicode character to locate.
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
- count
- A Int32 containing the range of the current instance at which to end searching.
A Int32 containing the index of the last occurrence of value in the current instance if found between startIndex and (startIndex - count + 1); otherwise, -1.
Exception Type Condition ArgumentNullException value is a null reference. ArgumentOutOfRangeException startIndex or count is less than zero. -or-
startIndex - count is less than -1.
This method is case-sensitive.
System.String Class, System Namespace
public int LastIndexOf(char value, int startIndex);
Returns the index of the last occurrence of a specified character within the current instance.
- value
- A Unicode character to locate.
- startIndex
- A Int32 containing the index in the current instance from which to begin searching.
A Int32 containing the index of the last occurrence of value in the current instance, if found; otherwise, -1.
Exception Type Condition ArgumentNullException value is a null reference. ArgumentOutOfRangeException startIndex is less than zero or greater than the length of the current instance.
This method searches for the last occurrence of the specified character between the start of the string and the indicated index.This method is case-sensitive.
The following example demonstrates the System.String.LastIndexOf(System.Char) method.
using System; public class StringLastIndexOfTest { public static void Main() { String str = "aa bb cc dd"; Console.WriteLine( str.LastIndexOf('d', 8) ); Console.WriteLine( str.LastIndexOf('b', 8) ); } }The output is
-1
4
System.String Class, System Namespace
public int LastIndexOf(char value);
Returns the index of the last occurrence of a specified character within the current instance.
- value
- The Unicode character to locate.
A Int32 containing the index of the last occurrence of value in the current instance, if found; otherwise, -1.
This method is case-sensitive.
System.String Class, System Namespace
public int LastIndexOfAny(char[] anyOf);
Returns the index of the last occurrence of any element of a specified array of characters in the current instance.
- anyOf
- An array of Unicode characters.
A Int32 containing the index of the last occurrence of any element of anyOf in the current instance, if found; otherwise, -1.
Exception Type Condition ArgumentNullException anyOf is a null reference.
This method is case-sensitive.
System.String Class, System Namespace
public int LastIndexOfAny(char[] anyOf, int startIndex);
Returns the index of the last occurrence of any element of a specified array of characters in the current instance.
- anyOf
- An array of Unicode characters.
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
A Int32 containing the index of the last occurrence of any element of anyOf in the current instance, if found; otherwise, -1.
Exception Type Condition ArgumentNullException anyOf is a null reference. ArgumentOutOfRangeException startIndex is less than zero or greater than or equal to the length of the current instance.
This method searches for the last occurrence of the specified characters between the start of the string and the indicated index.This method is case-sensitive.
System.String Class, System Namespace
public int LastIndexOfAny(char[] anyOf, int startIndex, int count);
Returns the index of the last occurrence of any of specified characters in the provided range of the current instance.
- anyOf
- An array of Unicode characters.
- startIndex
- A Int32 containing the index of the current instance from which to start searching.
- count
- A Int32 containing the range of the current instance at which to end searching.
A Int32 containing the index of the last occurrence of any element of anyOf if found between startIndex and (startIndex - count + 1); otherwise, -1.
Exception Type Condition ArgumentNullException anyOf is a null reference. ArgumentOutOfRangeException startIndex or count is less than zero. -or-
startIndex - count is smaller than -1.
The search begins at startIndex and continues until startIndex - count + 1. The character at startIndex - count is not included in the search.This method is case-sensitive.
System.String Class, System Namespace
public string PadLeft(int totalWidth);
Right-aligns the characters in the current instance, padding with spaces on the left, for a specified total length.
- totalWidth
- A Int32 containing the number of characters in the resulting string.
A new String that is equivalent to the current instance right-aligned and padded on the left with as many spaces as needed to create a length of totalWidth. If totalWidth is less than the length of the current instance, returns a new String that is identical to the current instance.
Exception Type Condition ArgumentException totalWidth is less than zero.
[Note: A space in Unicode format is defined as the hexadecimal value 0x20.]
System.String Class, System Namespace
public string PadLeft(int totalWidth, char paddingChar);
Right-aligns the characters in the current instance, padding on the left with a specified Unicode character, for a specified total length.
- totalWidth
- A Int32 containing the number of characters in the resulting string.
- paddingChar
- A Char that specifies the padding character to use.
A new String that is equivalent to the current instance right-aligned and padded on the left with as many paddingChar characters as needed to create a length of totalWidth . If totalWidth is less than the length of the current instance, returns a new String that is identical to the current instance.
Exception Type Condition ArgumentException totalWidth is less than zero.
System.String Class, System Namespace
public string PadRight(int totalWidth, char paddingChar);
Left-aligns the characters in the current instance, padding on the right with a specified Unicode character, for a specified total number of characters.
- totalWidth
- A Int32 containing the number of characters in the resulting string.
- paddingChar
- A Char that specifies the padding character to use.
A new String that is equivalent to the current instance left aligned and padded on the right with as many paddingChar characters as needed to create a length of totalWidth. If totalWidth is less than the length of the current instance, returns a new String that is identical to the current instance.
Exception Type Condition ArgumentException totalWidth is less than zero.
System.String Class, System Namespace
public string PadRight(int totalWidth);
Left-aligns the characters in the current instance, padding with spaces on the right, for a specified total number of characters.
- totalWidth
- A Int32 containing the number of characters in the resulting string.
A new String that is equivalent to this instance left aligned and padded on the right with as many spaces as needed to create a length of totalWidth. If totalWidth is less than the length of the current instance, returns a new String that is identical to the current instance.
Exception Type Condition ArgumentException totalWidth is less than zero.
System.String Class, System Namespace
public string Remove(int startIndex, int count);
Deletes a specified number of characters from the current instance beginning at a specified index.
- startIndex
- A Int32 containing the index of the current instance from which to start deleting characters.
- count
- A Int32 containing the number of characters to delete.
A new String that is equivalent to the current instance without the specified range characters.
Exception Type Condition ArgumentOutOfRangeException startIndex or count is less than zero. -or-
startIndex plus count is greater than the length of the current instance.
System.String Class, System Namespace
public string Replace(string oldValue, string newValue);
Replaces all instances of a specified substring within the current instance with another specified string.
- oldValue
- A String containing the string value to be replaced.
- newValue
- A String containing the string value to replace all occurrences of oldValue. Can be a null reference.
A String equivalent to the current instance with all occurrences of oldValue replaced with newValue. If the replacement value is a null reference, the specified substring is removed.
System.String Class, System Namespace
public string Replace(char oldChar, char newChar);
Replaces all instances of a specified Unicode character with another specified Unicode character.
- oldChar
- The Unicode character to be replaced.
- newChar
- The Unicode character to replace all occurrences of oldChar.
A String equivalent to the current instance with all occurrences of oldChar replaced with newChar.
System.String Class, System Namespace
public string[] Split(params char[] separator);
Returns substrings of the current instance that are delimited by the specified characters.
- separator
- A Char array of delimiters. Can be a null reference.
A String array containing the results of the split operation as follows:
Return Value Description A single-element array containing the current instance. None of the elements of separator are contained in the current instance. A multi-element String array, each element of which is a substring of the current instance that was delimited by one or more characters in separator. At least one element of separator is contained in the current instance. A multi-element String array, each element of which is a substring of the current instance that was delimited by white space characters. The current instance contains white space characters and separator is a null reference or an empty array.
System.String.Empty is returned for any substring where two delimiters are adjacent or a delimiter is found at the beginning or end of the current instance.Delimiter characters are not included in the substrings.
System.String Class, System Namespace
public string[] Split(char[] separator, int count);
Returns substrings of the current instance that are delimited by the specified characters.
- separator
- An array of Unicode characters that delimit the substrings in the current instance, an empty array containing no delimiters, or a null reference.
- count
- A Int32 containing the maximum number of array elements to return.
A String array containing the results of the split operation as follows:
Return Value Description A single-element array containing the current instance. None of the elements of separator are contained in the current instance. A multi-element String array, each element of which is a substring of the current instance that was delimited by one or more characters in separator At least one element of separator is contained in the current instance. A multi-element String array, each element of which is a substring of the current instance that was delimited by white space characters. The current instance contains white space characters and separator is a null reference or an empty array.
Exception Type Condition ArgumentOutOfRangeException count is negative.
System.String.Empty is returned for any substring where two delimiters are adjacent or a delimiter is found at the beginning or end of the current instance.Delimiter characters are not included in the substrings.
If there are more substrings in the current instance than the maximum specified number, the first count -1 elements of the array contain the first count - 1 substrings. The remaining characters in the current instance are returned in the last element of the array.
System.String Class, System Namespace
public bool StartsWith(string value);
Returns a Boolean value that indicates whether the start of the current instance matches the specified String.
- value
- A String .
true
if the start of the current instance is equal to value;false
if value is not equal to the start of the current instance or is longer than the current instance.
Exception Type Condition ArgumentNullException value is a null reference.
This method compares value with the substring at the start of the current instance that has a length of value.Length. If value.Length is greater than the length of the current instance or the relevant substring of the current instance is not equal to value, this method returnsfalse
; otherwise, this method returnstrue
.The comparison is case-sensitive.
System.String Class, System Namespace
public string Substring(int startIndex, int length);
Retrieves a substring from the current instance, starting from a specified index, continuing for a specified length.
- startIndex
- A Int32 containing the index of the start of the substring in the current instance.
- length
- A Int32 containing the number of characters in the substring.
A String containing the substring of the current instance with the specified length that begins at the specified position. Returns System.String.Empty if startIndex is equal to the length of the current instance and length is zero.
Exception Type Condition ArgumentOutOfRangeException length is greater than the length of the current instance. -or-
startIndex or length is less than zero.
System.String Class, System Namespace
public string Substring(int startIndex);
Retrieves a substring from the current instance, starting from a specified index.
- startIndex
- A Int32 containing the index of the start of the substring in the current instance.
A String equivalent to the substring that begins at startIndex of the current instance. Returns System.String.Empty if startIndex is equal to the length of the current instance.
Exception Type Condition ArgumentOutOfRangeException startIndex is less than zero or greater than the length of the current instance.
System.String Class, System Namespace
IEnumerator<Char> IEnumerable<Char>.GetEnumerator()
This method is implemented to support the System.Collections.Generics.IEnumerable<System.Char> interface.
System.String Class, System Namespace
IEnumerator IEnumerable.GetEnumerator();
Implemented to support the IEnumerable interface. [Note: For more information, see System.Collections.IEnumerable.GetEnumerator.]
System.String Class, System Namespace
public char[] ToCharArray();
Copies the characters in the current instance to a Unicode character array.
A Char array whose elements are the individual characters of the current instance. If the current instance is an empty string, the array returned by this method is empty and has a zero length.
System.String Class, System Namespace
public char[] ToCharArray(int startIndex, int length);
Copies the characters in a specified substring in the current instance to a Unicode character array.
- startIndex
- A Int32 containing the index of the start of a substring in the current instance.
- length
- A Int32 containing the length of the substring in the current instance.
A Char array whose elements are the length number of characters in the current instance, starting from the index startIndex in the current instance. If the specified length is zero, the entire string is copied starting from the beginning of the current instance, and ignoring the value of startIndex. If the current instance is an empty string, the returned array is empty and has a zero length.
Exception Type Condition ArgumentOutOfRangeException startIndex or length is less than zero. -or-
startIndex plus length is greater than the length of the current instance.
System.String Class, System Namespace
public string ToLower();
Returns a copy of this String in lowercase.
A String in lowercase..
This method takes into account the culture (if any) of the current thread.
System.String Class, System Namespace
public override string ToString();
Returns a String representation of the value of the current instance.
The current String.
[Note: This method overrides System.Object.ToString.]
System.String Class, System Namespace
public string ToString(IFormatProvider provider);
Returns this instance ofString
; no actual conversion is performed.
- provider
- (Reserved) A IFormatProvider interface implementation which supplies culture-specific formatting information.
ThisString
.
provider is reserved, and does not currently participate in this operation.
System.String Class, System Namespace
public string ToUpper();
Returns a copy of the current instance with all elements converted to uppercase, using default properties.
A new String in uppercase.
System.String Class, System Namespace
public string Trim(params char[] trimChars);
Removes all occurrences of a set of characters provided in a character Array from the beginning and end of the current instance.
- trimChars
- An array of Unicode characters. Can be a null reference.
A new String equivalent to the current instance with the characters in trimChars removed from its beginning and end. If trimChars is a null reference, all of the white space characters are removed from the beginning and end of the current instance.
System.String Class, System Namespace
public string Trim();
Removes all occurrences of white space characters from the beginning and end of the current instance.
A new String equivalent to the current instance after white space characters are removed from its beginning and end.
System.String Class, System Namespace
public string TrimEnd(params char[] trimChars);
Removes all occurrences of a set of characters specified in a Unicode character Array from the end of the current instance.
- trimChars
- An array of Unicode characters. Can be a null reference.
A new String equivalent to the current instance with characters in trimChars removed from its end. If trimChars is a null reference, white space characters are removed.
System.String Class, System Namespace
public string TrimStart(params char[] trimChars);
Removes all occurrences of a set of characters specified in a Unicode character array from the beginning of the current instance.
- trimChars
- An array of Unicode characters or a null reference.
A new String equivalent to the current instance with the characters in trimChars removed from its beginning. If trimChars is a null reference, white space characters are removed.
System.String Class, System Namespace
public static bool operator ==(String a, String b);
Returns a Boolean value indicating whether the two specified string values are equal to each other.
- a
- The first String to compare.
- b
- The second String to compare.
true
if a and b represent the same string value; otherwise,false
.
System.String Class, System Namespace
public static bool operator !=(String a, String b);
Returns a Boolean value indicating whether the two string values are not equal to each other.
- a
- The first String to compare.
- b
- The second String to compare.
true
if a and b do not represent the same string value; otherwise,false
.
System.String Class, System Namespace
public static readonly string Empty;
A constant string representing the empty string.
This field is read-only.This field is a string of length zero, "".
System.String Class, System Namespace
public char this[int index] { get; }
Gets the character at a specified position in the current instance.
A Unicode character at the location index in the current instance.
Exception Type Condition IndexOutOfRangeException index is greater than or equal to the length of the current instance or less than zero.
This property is read-only.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 its length - 1.
System.String Class, System Namespace
public int Length { get; }
Gets the number of characters in the current instance.
A Int32 containing the number of characters in the current instance.
This property is read-only.
The following example demonstrates the System.String.Length property.
using System; public class StringLengthExample { public static void Main() { string str = "STRING"; Console.WriteLine( "The length of string {0} is {1}", str, str.Length ); } }The output is
The length of string STRING is 6
System.String Class, System Namespace