Strings in C#

Introduction

In this article we will learn about Strings. As we know a string is a sequence of characters. In the C# language strings are objects of the built-in string data type. So we can say that a string is a reference type. String is C#'s name for the System.String standard .NET string type. Thus a C# string has access to all of the methods, properties, fields and operators defined by String.

The String Class

String is defined in the System namespace. It implements the IComparable, IComparable<string>, IClonable, IConvertible, IEnumerable<char> and IExecutable<string> interfaces. String is a sealed class so you cannot inherit from it. Let's try to understand String in details.

The String Constructors

The String class defines several constructors that allow us to understand a string in more then one way with more variety.

  • To create a string from a character array:

    public String(char[ ] value)
    public String(char[ ] value, int startIndex, int length)

    The first constructs a string that contains the characters in value. The second constructor uses length characters from value and begins at the index specified by startIndex.
     
  • A string having a character repeated a number of times:
    1. public String(char c, int count)  
    c specifies the character that will be repeated count times.
     
  • A string having a pointer to a character array
    1. public String(char* value)  
    2. public String(char* value, int startIndex, int length)  
    The first constructs a string that contains the characters pointed to by value. It is assumed that value points to a null-terminated array, that is used in its entirety. The second constructor uses length characters from the array pointed to by value, beginning at the index specified by startIndex. Because they use pointers, these constructors can be used only in unsafe code.
     
  • A string having a pointer of an array of bytes:
    1. public String(sbyte* value)  
    2. public String(sbyte* value, int startIndex, int length)  
    3. public String(sbyte* value, int startIndex, int length, Encoding enc)  
    The first constructs a string that contains the bytes pointed to by value. It's assumed that value points to a null-terminated array, that is used in its entirety. The second constructs uses length characters from the array pointed to by value, beginning at the index specified by startIndex. The third constructs specify how the bytes are encoded. The Encoding class is in the System.Text namespace. Because they use pointers, these constructors can only be used in unsafe code.

The String Operators

The String class overloads the two operators "==" and "!=". For the test of the two strings for equality, use the "==" operator. Normally, when the "==" operator is applied to object references, it determines if both references refer to the same object. This differs for objects of type String. When the "==" is applied to two String references, the contents of the strings, themselves, are compared for equality. The same is true for the "!=" operator: the contents of the strings are compared. However, the other relational operators, such as "<" or ">=", compare the references, just like they do for other types of objects. To determine if one string is greater than or less than another, use the Compare( ) or CompareTo( ) method defined by String.

The String Methods

The String class defines a large number of methods, some of the important methods are described below with an example.

Comparing Strings

String provides a wide array of comparison methods. They can compare two strings in their entirety or in parts. It can use case-sensitive comparisons or ignore case. We can also specify how the comparison is done by using a version that has a StringComparison parameter, or what cultural information governs the comparison using a version that has a CultureInfo parameter. The overloads of Compare( ) that do not include a StringComparison are case-sensitive and culture-sensitive.

  1. using System;  
  2. namespace stringComparision  
  3. {  
  4.   
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             string str1 = "password";  
  10.             string str2 = "Password";  
  11.             string str3 = "UserName";  
  12.             string str4 = "password";  
  13.    
  14.             int result;  
  15.             result = String.Compare(str1, str2, StringComparison.CurrentCulture);  
  16.             Console.Write("Using a culture-sensitive comparison: ");  
  17.             if (result < 0)  
  18.                 Console.WriteLine(str1 + " is less than " + str2);  
  19.             else if (result > 0)  
  20.                 Console.WriteLine(str1 + " is greater than " + str2);  
  21.             else  
  22.                 Console.WriteLine(str1 + " equals " + str2);  
  23.               
  24.             result = String.Compare(str1, str2, StringComparison.Ordinal);  
  25.             Console.Write("Using an ordinal comparison: ");  
  26.             if (result < 0)  
  27.                 Console.WriteLine(str1 + " is less than " + str2);  
  28.             else if (result > 0)  
  29.                 Console.WriteLine(str1 + " is greater than " + str2);  
  30.             else  
  31.                 Console.WriteLine(str1 + " equals " + str4);  
  32.              
  33.             result = String.CompareOrdinal(str1, str2);  
  34.             Console.Read();  
  35.             Console.Write("Using CompareOrdinal(): ");  
  36.             if (result < 0)  
  37.                 Console.WriteLine(str1 + " is less than " + str2);  
  38.             else if (result > 0)  
  39.                 Console.WriteLine(str1 + " is greater than " + str2);  
  40.             else  
  41.                 Console.WriteLine(str1 + " equals " + str4);  
  42.             Console.WriteLine();  
  43.              
  44.             if (str1 == str4) Console.WriteLine(str1 + " == " + str4);  
  45.              
  46.             if (str1 != str3) Console.WriteLine(str1 + " != " + str3);  
  47.             if (str1 != str2) Console.WriteLine(str1 + " != " + str2);  
  48.             Console.WriteLine();  
  49.              
  50.             if (String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))  
  51.                 Console.WriteLine("Using Equals() with OrdinalIgnoreCase, " +  
  52.                 str1 + " equals " + str2);  
  53.               
  54.          }  
  55.     }  
  56. }  

 StringComp

Concatenating Strings

When we are adding two different strings into a single one we call them concatenation. The method that performs concatenation is called Concat( ).

  1. public static string Concat(string str0, string str1)  
This method returns a string that contains str1 concatenated to the end of str0. Another form of Concat( ).
  1. public static string Concat(string str0, string str1, string str2)  
  2.   
  3. public static string Concat(string str0, string str1, string str2, string str3)  
  4.   
  5. public static string Concat(params string[ ] values)  

 

  1. using System;  
  2. namespace StringConcat  
  3.   
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             string str = String.Concat("This ""is ""a ",  
  10.                                           "test ""of ""the ",  
  11.                                           "String ""class.");  
  12.             Console.WriteLine("Result: " + str);  
  13.             Console.Read();  
  14.         }  
  15.     }  
  16. }  

 ConCat

The .NET 4.0 Framework adds two more forms of Concat( ), they are:

  1. public static string Concat<T>(IEnumerable<T> values)  
  2. public static string Concat(IEnumerable<string> values)  
The first method returns a string that contains the concatenation of the string representation of the values in values, that can be of any type of object that implements IEnumerable<T>. The second form concatenates the strings specified by values.

NOTE: If you are doing a large amount of string concatenations, then using a StringBuilder may be a better choice.

Searching a String

Searching a string is an important task in any language. We use the IndexOf( ) method. This method is useful in searching from the string. It defines several overloaded forms. Here is one that searches for the first occurrence of a character within a string:

public int IndexOf(char value)

This method returns the index of the first occurrence of the character value within the invoking string. It returns –1 if the value is not found.
  1. public int IndexOf(String value)  
  2.   
  3. public int IndexOf(String value, StringComparison comparisonType)  
The first method uses a culture-sensitive search to find the first occurrence of the string referred to by value. The second method specifies a StringComparison value that specifies how the search is conducted. Both returns –1 if the item is not found.

To search for the last occurrence of a character or a string, we use the LastIndexOf( ) method. It also defines several overloaded forms. This one searches for the last occurrence of a character within the invoking string:
  1. public int LastIndexOf(char value)  
This method uses an ordinal search and returns the index of the last occurrence of the character value within the invoking string or –1 if the value is not found.
  1. public int LastIndexOf(string value)  
  2. public int LastIndexOf(string value, StringComparison comparisonType)  
The first method uses a culture-sensitive search to find the first occurrence of the string referred to by value. The second form let's you specify a StringComparison value that specifies how the search is conducted. Both return –1 if the item is not found. 

 

  1. using System;  
  2. namespace StringSrch  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             string str = "C# has powerful string language.";  
  9.             int no;  
  10.             Console.WriteLine("str: " + str);  
  11.             no = str.IndexOf('h');  
  12.             Console.WriteLine("Index of first 'h': " + no);  
  13.             no = str.LastIndexOf('h');  
  14.             Console.WriteLine("Index of last 'h': " + no);  
  15.             no = str.IndexOf("ing", StringComparison.Ordinal);  
  16.             Console.WriteLine("Index of first \"ing\": " + no);  
  17.             no = str.LastIndexOf("ing", StringComparison.Ordinal);  
  18.             Console.WriteLine("Index of last \"ing\": " + no);  
  19.             char[] chrs = { 'a''b''c' };  
  20.             no = str.IndexOfAny(chrs);  
  21.             Console.WriteLine("Index of first 'a', 'b', or 'c': " + no);  
  22.             if (str.StartsWith("C# has", StringComparison.Ordinal))  
  23.                 Console.WriteLine("str begins with \"C# has\"");  
  24.             if (str.EndsWith("age.", StringComparison.Ordinal))  
  25.                 Console.WriteLine("str ends with \"ling.\"");  
  26.             Console.Read();  
  27.         }  
  28.     }  
  29. }  
srchString

Inserting, Removing and Replacing

There is a method Insert() to insert a string into another.

  1. public string Insert(int startIndex, string value)  
The method referred to by value is inserted into the invoking string at the index specified by startIndex. The resulting string is returned.

We can remove a portion of a string using Remove( ) as in the following:
  1. public string Remove(int startIndex)  
  2. public string Remove(int startIndex, int count)  
The first method  begins at the index specified by startIndex and removes all remaining characters in the string. The second method begins at startIndex and removes count number of characters. In both cases, the resulting string is returned.

We can replace a portion of a string using Replace( ).
  1. public string Replace(char oldChar, char newChar)  
  2. public string Replace(string oldValue, string newValue)  
The first method replaces all occurrences of oldChar in the invoking string with newChar. The second method replaces all occurrences of the string referred to by oldValue in the invoking string with the string referred to by newValue. In both cases, the resulting string is returned. 

  1. using System;  
  2. namespace editString  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             string str = "This test";  
  9.             Console.WriteLine("Original string: " + str);  
  10.             str = str.Insert(5, "is a ");  
  11.             Console.WriteLine(str);  
  12.             str = str.Replace("is""was");  
  13.             Console.WriteLine(str);  
  14.             str = str.Replace('a''X');  
  15.             Console.WriteLine(str);  
  16.             str = str.Remove(4, 5);  
  17.             Console.WriteLine(str);  
  18.             Console.Read();  
  19.         }  
  20.     }  
  21. }  
insertUpdate

Summary

In this article we learned various aspects of string methods. We have also seen the String class and constructors. The importance of and use in real programming. After reading this article we will be able to understand the basics of the string class. 


Similar Articles