12.1. The System.String Class

Java and C# strings are immutable, and therefore the string instance cannot be modified. Instead, a new instance containing the modification is created whenever a method is called on a string instance that tries to modify it. The .NET Framework class library gives the following class declaration for the System.String class. (If you prefer, you can skip this section and use it as a reference when you start using some of the methods in this class.)

[Serializable]
public sealed class String : IComparable, ICloneable,
IConvertible, IEnumerable

The IComparable interface is similar to the java.lang.Comparable interface. An object implements this interface in order to compare itself to another object of the same type. The interface contains a CompareTo method, which returns a value of –1, 0, or 1 depending on whether the instance is less than, equal to, or greater than the object passed to the argument. Because a string is a sequence of characters, this class implements the IEnumerable interface, which returns an IEnumerator. This interface lets you iterate over the sequence of characters. The IConvertible interface defines methods that convert the value of the implementing reference or value type to a Common Language Runtime type that has an equivalent value. The CLR typically exposes the IConvertible interface through the Convert class.

Listing 12.1 shows how the String interfaces can be useful.

Listing 12.1. Using the System.String Interfaces (C#)
using System;
using System.Collections;

public class Test {

  public static void Main(string[] args) {

    TestIComparable();
    TestIEnumerable();
    TestICloneable();
    TestIConvertible();
  }
  private static void TestIComparable() {
    String s1 = "C#";
    String s2 = "Java";
    Console.WriteLine("Comparing C# and Java
                       "+s1.CompareTo(s2));
  }
  private static void TestICloneable() {
    String s1 = "C#";
    String s2 = (String) s1.Clone();
    Console.WriteLine("(s1 Equals s2)? "+s1.Equals(s2));
    Console.WriteLine("(s1 == s2)? " + (s1 == s2));
  }
  private static void TestIEnumerable() {
    String s1 = "abcdefghijklmnopqrstuvwxyz";
    IEnumerator enums = s1.GetEnumerator();
    while (enums.MoveNext()) {
      Console.Write(enums.Current);
    }
  }
  private static void TestIConvertible() {
    String s = "12345";
    try {
      Console.WriteLine(Convert.ToInt16(s));
      Console.WriteLine(Convert.ToInt32(s));
      Console.WriteLine(Convert.ToInt64(s));
      Console.WriteLine(Convert.ToDecimal(s));
      Console.WriteLine(Convert.ToDouble(s));
      Console.WriteLine(Convert.ToBoolean(s));
    } catch (Exception e) {
      Console.WriteLine(e.Message);
    }
  }
}

The output of Listing 12.1 is as follows:

Comparing C# and Java -1
abcdefghijklmnopqrstuvwxyz(s1 Equals s2)? True
(s1 == s2)? True
12345
12345
12345
12345
12345
String was not recognized as a valid Boolean.

Note that the Convert class is a utility class found in the System namespace that can be used to convert from one data type to another. Converting the string 12345 to a bool throws an exception, and this is indicated by the last line of the output.

The String class is declared as sealed, which is similar to the final declaration of Java strings. The System.String class cannot be subclassed. The System.String class is thread-safe. Thread safety may be inconsequential for this class, considering that objects of this class cannot be changed by any thread. Tables 12.1 and 12.2 list the constructors and methods, respectively, of the System.String class.

String constructors are seldom used to initialize strings. A traditional approach is to assign the string reference to a string literal; the runtime automatically creates a string object and makes the reference point to this string object. The C# runtime optimizes creation of Strings (just as the JVM does) through the process of interning; essentially, this means that strings with the same value are represented by one object in the runtime, with multiple references pointing to the same object. This technique minimizes object creation, given that Strings are ubiquitous. Both the CLR and the JVM perform this optimization internally. One constructor that Java programmers may miss in C# is the one that takes a string literal.

Table 12.1. CLS-Compliant Public Constructors of the String Class
ConstructorDescription
public String(char[])Initializes a new instance of the String class to the value indicated by an array of Unicode characters
public String(char, int)Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times
public String(char[], int, int)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

Table 12.2 shows the CLS-compliant public methods of the String class. The compare methods make a lexical comparison of the compared string instances. The int returned in all the compare methods is 0 if the strings are equal, –1 if the first string is less than the second one, and 1 if the first string is greater than the second string. Note that all the compare methods base their comparison on comparing the values of the strings.

Table 12.3 shows the compare methods of the String class. The CompareTo method compares one String instance to another. Note that this method is not static and is defined on the string object itself. Again, the method makes a lexical comparison, resulting in 0 if the two objects are equal, –1 if the instance is less than the value, and 1 if the instance is greater than the value.

Table 12.4 shows the concatenation methods of the String class. Notice that the Concat methods are all static. Two strings concatenated twice by the same method will yield two different string instances. You can test this by using the = = operator to compare the object instances, as shown in Listing 12.2.

Table 12.2. CLS-Compliant Methods of the String Class
Constructor/Public MethodDescription
public object Clone()Returns a reference to a copy of String.
public static int Compare(string, string)Compares two String objects.
public static int Compare(string, string, bool)Compares two strings, ignoring or honoring their case.
public static int Compare(string, string, bool, CultureInfo)Compares two specified String objects, ignoring or honoring their case, and honoring culture-specific information about their formatting.
public static int Compare(string, int, string, int, int)Compares substrings of two specified String objects.
public static int Compare(string, int, string, int, int, bool)Compares substrings of two specified String objects, ignoring (bool = true) or honoring (bool = false) their case.
public static int Compare(string, int, string, int, int, bool, CultureInfo);Compares substrings of two specified String objects, ignoring or honoring their case, and honoring culture-specific information about their formatting. CultureInfo is similar to the Locale information in Java.
public static int CompareOrdinal (string, string)Compares two specified String objects without considering the local language or culture.
public static int CompareOrdinal (string, int, string, int, int)Compares substrings of two specified String objects without considering the local language or culture. Parameters specify the length and starting positions of the substrings.

Listing 12.2. Comparing Concatenated Instances of a String (C#)
using System;
public class Test {
  public static void Main(string[] args) {
    String s = String.Concat("a", "b");
    String t = String.Concat("a", "b");
    Console.WriteLine(s == t);
  }
}

Table 12.3. Compare Methods of the String Class
MethodDescription
public int CompareTo(object)Compares this instance with a specified Object
public int CompareTo(string)Compares this instance with a specified String object

Table 12.4. Concatenation Methods of the String Class
MethodDescription
public static string Concat(object)Creates the String representation of a specified object
public static string
  Concat(params object[])

Concatenates the String representations of the elements in a specified Object array
public static string
  Concat(params string[]);

Concatenates the elements of a specified String array
public static string
  Concat(object, object)

Concatenates the String representations of two specified objects
public static string Concat(string,
  string)

Concatenates two strings
public static string
  Concat(object, object, object)

Concatenates the String representations of three specified objects
public static string Concat(string,
  string, string);

Concatenates three strings
public static string Concat(string,
  string, string, string)

Concatenates four strings

The output of Listing 12.2 is

True

The CLR does string interning in which String instances are reused. In Listing 12.2 we created two different strings (s and t) by concatenating the string literals a and b. The two string instances s and t point to the same string object.

Table 12.5 shows an assortment of methods in the String class. Most of the methods in Table 12.5 are self-explanatory, and therefore we will not give examples for each of the member methods. Remember that methods that seem to modify the string return a new string that is different from the original string. Listing 12.3 demonstrates this point.

Listing 12.3. Testing String Equality (C#)
using System;

public class StringTest {

  public static void Main(string[] args) {
    string s = "hello ";
    String t = s.Insert(s.Length-1, "World").Remove(s.Length-
    1,5);
    Console.WriteLine(s == t);
    Console.WriteLine(s.Equals(t));
    Console.WriteLine((object)s == (object)t);
  }
}

The output of Listing 12.3 is as follows:

True
True
False

Although s and t have the same value, they are two different string object instances (not interned) because we made some modifications on the string instance s.

Table 12.5. An Assortment of Methods in the String class
MethodDescription
public static string
  Copy(string str)

Creates a new instance of String with the same value as a specified String.
public void CopyTo (
  int sourceIndex,
  char[] destination,
  int destinationIndex,
  int count
  )

Copies a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.
public bool EndsWith(
  string value
  )

Determines whether the end of this instance matches the specified String.
public override bool
  Equals(object)

Determines whether this instance of String and a specified object, which must be a String, have the same value.
public override bool
  Equals(string)

Determines whether this instance and a specified String have the same value.
public static bool
  Equals(string, string)

Determines whether two specified String objects have the same value.
public static string
  Format(string, object)

Replaces the format specification in a specified String with the textual equivalent of the value of a specified Object instance.
public static string
  Format(string, params
  object[])

Replaces the format specification in a specified String with the textual equivalent of the value of a corresponding Object instance in a specified array.
public static string
  Format(IFormatProvider,
  string, params object[])

Replaces the format specification in a specified String with the textual equivalent of the value of a corresponding Object instance in a specified array. A specified parameter supplies culture-specific formatting information.
public static string
  Format(string, object,
  object)

Replaces the format specification in a specified String with the textual equivalent of the value of two specified Object instances.
public static string
  Format(string, object,
  object, object)

Replaces the format specification in a specified String with the textual equivalent of the value of three specified Object instances.
public CharEnumerator
  GetEnumerator()

Retrieves an object that can iterate through the individual characters in this instance.
public override int
  GetHashCode()

Returns the hash code for this instance.
public Type GetType()Gets the type of the current instance.
public TypeCode
  GetTypeCode()

Returns the TypeCode for class String.
public int
  IndexOf(char)

Returns the index of the first occurrence of the specified Unicode character in this instance.
public int
  IndexOf(string)

Returns the index of the first occurrence of the specified String in this instance.
public int IndexOf(char,
  int)

Returns the index of the first occurrence of the specified Unicode character in this instance. The search starts at a specified character position.
public int
  IndexOf(string, int)

Returns the index of the first occurrence of the specified String in this instance. The search starts at a specified character position.
public int IndexOf(char,
  int, int)

Returns the 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.
public int
  IndexOf(string,
  int, int)

Returns the 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.
public int
  IndexOfAny(char[])

Returns the index of the first occurrence in this instance of any character in a specified array of Unicode characters.
public int
  IndexOfAny(char[], int)

Returns the 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.
public int
  IndexOfAny(char[],
  int, int)

Returns the 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.
public string Insert(
  int startIndex,
  string value)

Inserts a specified instance of String at a specified index position in this instance.
public static string
  IsInterned(string str)

Retrieves a reference to a specified String.
public static string
  Join (string
  separator, string[]
  value, int startIndex,
  int count
  )

Concatenates a specified separator String between each element of a specified String array, yielding a single concatenated string.
public static string
  Join(string, string[],
  int, int)

Concatenates a specified separator String between each element of a specified String array, yielding a single concatenated string. Parameters specify the first array element and the number of elements to use.
public int
  LastIndexOf(char)

Returns the index position of the last occurrence of a specified Unicode character within this instance.
public int
  LastIndexOf(string)

Returns the index position of the last occurrence of a specified String within this instance.
public int
  LastIndexOf(char,
  int)

Returns the index position of the last occurrence of a specified Unicode character within this instance. The search starts at a specified character position.
public int
  LastIndexOf(string,
  int)

Returns the index position of the last occurrence of a specified String within this instance. The search starts at a specified character position.
public int
  LastIndexOf(char,
  int, int)

Returns the 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 examines a specified number of character positions.
public int
  LastIndexOf(string,
  int, int)

Returns the index position of the last occurrence of a specified String within this instance. The search starts at a specified character position and examines a specified number of character positions.
public int
  LastIndexOfAny(char[])

Returns the index position of the last occurrence in this instance of one or more characters specified in a Unicode array.
public int
  LastIndexOfAny
  (char[], int)

Returns the 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.
public int
  LastIndexOfAny(char[],
  int, int)

Returns the 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 examines a specified number of character positions.
public string
  PadLeft(int)

Right-aligns the characters in this instance, padding with spaces on the left for a specified total length.
public string
  PadLeft(int, char)

Right-aligns the characters in this instance, padding on the left with a specified Unicode character for a specified total length.
public string
  PadRight(int)

Left-aligns the characters in this string, padding with spaces on the right for a specified total length.
public string
  PadRight(int, char)

Left-aligns the characters in this string, padding on the right with a specified Unicode character for a specified total length.
public string Remove(
  int startIndex,
  int count
  )

Deletes a specified number of characters from this instance beginning at a specified position.
public string
  Replace(char, char)

Replaces all occurrences of a specified Unicode character in this instance with another specified Unicode character.
public string
  Replace(string, string)

Replaces all occurrences of a specified String in this instance with another specified String.
public string[]
  Split(char[])

Identifies the substrings in this instance that are delimited by one or more characters specified in an array, and then places the substrings into a String array.
public string[]
  Split(char[], int)

Identifies the substrings in this instance that are delimited by one or more characters specified in an array, and then places the substrings into a String array. A parameter specifies the maximum number of array elements to return.
public bool
  StartsWith(string
  value)

Determines whether the beginning of this instance matches the specified String.
public string
  Substring(int)

Retrieves a substring from this instance. The substring starts at a specified character position.
public string
  Substring(int, int)

Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.
public char[]
  ToCharArray()

Copies the characters in this instance to a Unicode character array.
public char[]
  ToCharArray(int, int)

Copies the characters in a specified substring in this instance to a Unicode character array.
public string ToLower()Returns a copy of this String in lowercase.
public string
  ToLower(CultureInfo)

Returns a copy of this String in lowercase, taking into account specified culture-specific information.
public override
  string ToString()

Returns this instance of String; no actual conversion is performed.
public string
  ToString(IFormat
  Provider)

Returns this instance of String; no actual conversion is performed.
public string ToUpper()Returns a copy of this String in uppercase, using default properties.
public string
  ToUpper(CultureInfo)

Returns a copy of this String in uppercase, taking into account culture-specific information.
public string Trim()Removes all occurrences of white space characters from the beginning and end of this instance.
public string
  Trim(params char[])

Removes all occurrences of a set of characters specified in a Unicode character array from the beginning and end of this instance.
public string TrimEnd(
  params char[]
  trimChars)

Removes all occurrences of a set of characters specified in a Unicode character array from the end of this instance.
public string
  TrimStart(params
  char[] trimChars)

Removes all occurrences of a set of characters specified in a Unicode character array from the beginning of this instance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.90.131