C sharp - Common String Methods in C#
What is a String in C#?
A string in C# is a sequence of characters enclosed in double quotes ("
). It's an object of the System.String
class, which provides many built-in methods to manipulate and work with text.
Common String Methods in C#
Method | Description |
---|---|
Length |
Gets the number of characters in the string |
ToUpper() |
Converts all characters to uppercase |
ToLower() |
Converts all characters to lowercase |
Substring() |
Extracts part of the string |
IndexOf() |
Returns index of first occurrence of a char or substring |
Contains() |
Checks if a substring exists |
Replace() |
Replaces one value with another |
Trim() |
Removes whitespace from both ends |
Split() |
Splits the string into an array using a delimiter |
Equals() |
Compares two strings |
1. Length
– Get the number of characters
string name = "Hello";
Console.WriteLine(name.Length); // Output: 5
2. ToUpper()
and ToLower()
– Convert case
string name = "ChatGPT";
Console.WriteLine(name.ToUpper()); // Output: CHATGPT
Console.WriteLine(name.ToLower()); // Output: chatgpt
3. Substring()
– Get part of the string
string message = "Hello World";
Console.WriteLine(message.Substring(6)); // Output: World
Console.WriteLine(message.Substring(0, 5)); // Output: Hello
4. IndexOf()
– Find character or word index
string text = "C# Programming";
Console.WriteLine(text.IndexOf("g")); // Output: 6
5. Contains()
– Check if text exists
string sentence = "Learn C# with examples";
Console.WriteLine(sentence.Contains("C#")); // Output: True
6. Replace()
– Replace part of string
string sentence = "I like Java";
Console.WriteLine(sentence.Replace("Java", "C#")); // Output: I like C#
7. Trim()
– Remove whitespace
string userInput = " Hello ";
Console.WriteLine(userInput.Trim()); // Output: "Hello"
8. Split()
– Break string into words
string fruits = "Apple,Banana,Cherry";
string[] result = fruits.Split(',');
foreach (string fruit in result)
{
Console.WriteLine(fruit);
}
Output:
Apple
Banana
Cherry
9. Equals()
– Compare strings
string a = "hello";
string b = "Hello";
Console.WriteLine(a.Equals(b)); // False (case-sensitive)
Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase)); // True