C# String
In C#, you can use character arrays to represent strings, however, the more common practice is to usestringthe keyword to declare a string variable. The string keyword isSystem.StringAlias of a class.
Create a String object
You can create a string object 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 a formatting method to convert a value or object to its string representation
The following example demonstrates this:
Example
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
// String, string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
// By using the string constructor
char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
// Method returns a string
string[] sarray = { "Hello", "From", "Tutorials", "Point" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
// Formatting method used 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:
| Serial Number | Property name & description |
|---|---|
| 1 | Chars in the currentStringRetrieve from objectCharThe specified position of the object. |
| 2 | Length In the currentStringObtain the number of characters in the 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:
| Serial Number | Method name & description |
|---|---|
| 1 | public static int Compare(
string strA,
string strB
)
Compares two specified string objects and returns an integer indicating their relative position in sort order. This method is case-sensitive. |
| 2 | public static int Compare(
string strA,
string strB,
bool ignoreCase
)
Compares two specified string objects and returns an integer indicating their relative position in sort order. However, if the Boolean parameter is true, this method is case-insensitive. |
| 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 occurs within the 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 the string object to a specified position in a Unicode character array. |
| 9 | public bool EndsWith(
string value
)
Determines whether the end of the 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 a specified Unicode character in the current string. |
| 14 | public int IndexOf(
string value
)
Returns the index of the first occurrence of the specified string in this instance, with the index starting from 0. |
| 15 | public int IndexOf(
char value,
int startIndex
)
Returns the index of the first occurrence of the specified Unicode character, searching from the specified character position in this string, with the index starting from 0. |
| 16 | public int IndexOf(
string value,
int startIndex
)
Returns the index of the first occurrence of the specified string, searching from the specified character position in this instance, with the index starting from 0. |
| 17 | public int IndexOfAny(
char[] anyOf
)
Returns the index of the first occurrence of any character in a specified Unicode character array in this instance, with the index starting from 0. |
| 18 | public int IndexOfAny(
char[] anyOf,
int startIndex
)
Returns the index of the first occurrence of any character in a specified Unicode character array, searching from the specified character position in this instance, with the index starting from 0. |
| 19 | public string Insert(
int startIndex,
string value
)
Returns a new string in which a specified string is inserted at the specified index position of the current 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(
string separator,
string[] value
)
Concatenates all elements in a string array, using a specified separator to separate each element. |
| 22 | public static string Join(
string separator,
string[] value,
int startIndex,
int count
)
Concatenates the specified elements starting from a specified position in a string array, using a specified separator to separate each element. |
| 23 | public int LastIndexOf(
char value
)
Returns the zero-based index of the last occurrence of a specified Unicode character in the current string object. |
| 24 | public int LastIndexOf(
string value
)
Returns the zero-based index of the last occurrence of a specified string in the current string object. |
| 25 | public string Remove(
int startIndex
)
Removes all characters in the current instance, starting from a specified position and continuing to the last position, and returns the string. |
| 26 | public string Remove(
int startIndex,
int count
)
Removes a specified number of characters from a specified position in the current string and returns the string. |
| 27 | public string Replace(
char oldChar,
char newChar
)
Replaces all specified Unicode characters in the current string object with another specified Unicode character and returns a new string. |
| 28 | public string Replace(
string oldValue,
string newValue
)
Replaces all specified strings in the current string object with another specified string and returns a new string. |
| 29 | public string[] Split(
params char[] separator
)
Returns a string array containing the substrings of the current string object, delimited by elements of a specified Unicode character array. |
| 30 | public string[] Split(
char[] separator,
int count
)
Returns a string array containing the substrings of 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(
string value
)
Determines whether the beginning of the string instance matches the specified string. |
| 32 | public char[] ToCharArray() Returns a Unicode character array containing all characters in the current string object. |
| 33 | public char[] ToCharArray(
int startIndex,
int length
)
Returns a Unicode character array containing all characters in the current string object, starting from a specified index up to a specified length. |
| 34 | public string ToLower() Converts the string to lowercase and returns it. |
| 35 | public string ToUpper() Converts the string to uppercase and returns it. |
| 36 | public string Trim() Removes all leading and trailing whitespace characters from the current String object. |
The above list of methods is not exhaustive; please visit the MSDN library to see the complete list of methods and String class constructors.
Example
The following example demonstrates some of the methods mentioned above:
Compare strings
Example
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
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.
Get substring:
Example
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() ;
}
}
}
Run Example »
When the above code is compiled and executed, it produces the following result:
Last night I dreamt of San Pedro San Pedro
Connection string:
Example
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 stopother extensions