C# String
In C#, you can represent strings using character arrays, but it is more common to declare a string variable using the string keyword. The string keyword is an alias for the System.String class.
Creating String Objects
You can create string objects using one of the following methods:
- By assigning a string to a String variable
- By using a String class constructor
- By using the string concatenation operator (+)
- By retrieving a property or calling a method that returns a string
- By using formatting methods to convert a value or object to its string representation
The following example demonstrates this:
Example
using System;
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
// String concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
// Using the string constructor
char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
// Methods that return a string
string[] sarray = { "Hello", "From", "Tutorials", "Point" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
// Formatting methods to convert values
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}",
waiting);
Console.WriteLine("Message: {0}", chat);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Full Name: RowanAtkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 17:58 on Wednesday, 10 October 2012
Properties of the String Class
The String class has the following two properties:
No. | Property Name & Description |
---|---|
1 | Chars <br>Gets the Char object at a specified position in the current String object. |
2 | Length <br>Gets the number of characters in the current String object. |
Methods of the String Class
The String class has many methods for manipulating string objects. The following table provides some of the most commonly used methods:
No. | Method Name & Description |
---|---|
1 | public static int Compare(<br> string strA,<br> string strB<br>) <br>Compares two specified string objects and returns an integer that indicates their relative position in the sort order. This method is case-sensitive. |
2 | public static int Compare(<br> string strA,<br> string strB,<br> bool ignoreCase<br>) <br>Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, this method is case-insensitive if the boolean parameter is true. |
3 | public static string Concat( |
string str0, string str1 ) Concatenates two string objects. | 4 | public static string Concat( string str0, string str1, string str2 ) Concatenates three string objects. | 5 | public static string Concat( string str0, string str1, string str2, string str3 ) Concatenates four string objects. | 6 | public bool Contains( string value ) Returns a value indicating whether a specified string object occurs within this string. | 7 | public static string Copy( string str ) Creates a new String object with the same value as the specified string. | 8 | public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count ) Copies a specified number of characters from a specified position in this string object to a specified position in a Unicode character array. | 9 | public bool EndsWith( string value ) Determines whether the end of this string object matches the specified string. | 10 | public bool Equals( string value ) Determines whether the current string object has the same value as the specified string object. | 11 | public static bool Equals( string a, string b ) Determines whether two specified string objects have the same value. | 12 | public static string Format( string format, Object arg0 ) Replaces one or more format items in a specified string with the string representation of a specified object. | 13 | public int IndexOf( char value ) Returns the zero-based index of the first occurrence of the specified Unicode character in this string. | 14 | public int IndexOf( string value ) Returns the zero-based index of the first occurrence of the specified string in this instance. | 15 | public int IndexOf( char value, int startIndex ) Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting the search at the specified character position. | 16 | public int IndexOf( string value, int startIndex ) Returns the zero-based index of the first occurrence of the specified string in this instance, starting the search at the specified character position. | 17 | public int IndexOfAny( char[] anyOf ) Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. | 18 | public int IndexOfAny( char[] anyOf, int startIndex ) Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting the search at the specified character position. | 19 | public string Insert( int startIndex, string value ) Returns a new string in which a specified string is inserted at a specified index position in this string object. | 20 | public static bool IsNullOrEmpty( string value ) Indicates whether the specified string is null or an empty string. | 21 | public static string Join(<br> string separator,<br> string[] value<br>) <br>Concatenates all the elements of a string array, using the specified separator between each element. | | 22 | public static string Join(<br> string separator,<br> string[] value,<br> int startIndex,<br> int count<br>) <br>Concatenates the specified elements of a string array, starting at the specified index and up to the specified count, using the specified separator between each element. | | 23 | public int LastIndexOf(<br> char value<br>) <br>Returns the zero-based index position of the last occurrence of the specified Unicode character in the current string object. | | 24 | public int LastIndexOf(<br> string value<br>) <br>Returns the zero-based index position of the last occurrence of the specified string in the current string object. | | 25 | public string Remove(<br> int startIndex<br>) <br>Removes all characters from the current instance, starting at the specified position and continuing through the last position, and returns the string. | | 26 | public string Remove(<br> int startIndex,<br> int count<br>) <br>Removes the specified number of characters from the current string starting at the specified position and returns the string. | | 27 | public string Replace(<br> char oldChar,<br> char newChar<br>) <br>Replaces all occurrences of a specified Unicode character in the current string object with another specified Unicode character and returns the new string. | | 28 | public string Replace(<br> string oldValue,<br> string newValue<br>) <br>Replaces all occurrences of a specified string in the current string object with another specified string and returns the new string. | | 29 | public string[] Split(<br> params char[] separator<br>) <br>Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. | | 30 | public string[] Split(<br> char[] separator,<br> int count<br>) <br>Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return. | | 31 | public bool StartsWith(<br> string value<br>) <br>Determines whether the beginning of this string instance matches the specified string. | | 32 | public char[] ToCharArray() <br>Returns a Unicode character array with all the characters in the current string object. | | 33 | public char[] ToCharArray(<br> int startIndex,<br> int length<br>) <br>Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length. | | 34 | public string ToLower() <br>Converts the string to lowercase and returns it. | | 35 | public string ToUpper() <br>Converts the string to uppercase and returns it. | | 36 | public string Trim() <br>Removes all leading and trailing white-space characters from the current String object. |
The above method list is not exhaustive. Please visit the MSDN library for the complete list of methods and constructors for the String class.
Example
The following example demonstrates some of the methods mentioned above:
Comparing Strings
Example
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str1 = "This is test";
string str2 = "This is text";
if (String.Compare(str1, str2) == 0)
{
Console.WriteLine(str1 + " and " + str2 + " are equal.");
}
else
{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey();
When the above code is compiled and executed, it produces the following result:
This is test and This is text are not equal.
String Contains String:
Example
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "This is test";
if (str.Contains("test"))
{
Console.WriteLine("The sequence 'test' was found.");
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
The sequence 'test' was found.
Getting Substring:
Example
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "Last night I dreamt of San Pedro";
Console.WriteLine(str);
string substr = str.Substring(23);
Console.WriteLine(substr);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Last night I dreamt of San Pedro
San Pedro
Concatenating Strings:
Example
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string[] starray = new string[]{"Down the way nights are dark",
"And the sun shines daily on the mountain top",
"I took a trip on a sailing ship",
"And when I reached Jamaica",
"I made a stop"};
string str = String.Join("\n", starray);
Console.WriteLine(str);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Down the way nights are dark
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop