Various String Class Methods in C#
Introduction to String Methods in C#
The string
class in C# provides a wide range of methods for manipulating, comparing, and querying strings. These methods make it easier to perform common operations such as concatenation, searching, splitting, and formatting strings.
Concat() Method
The Concat()
method is used to concatenate multiple strings into a single string.
Example: Using Concat() Method
string firstName = "John";
string lastName = "Doe";
string fullName = string.Concat(firstName, " ", lastName);
Console.WriteLine(fullName); // Output: John Doe
In this example, the Concat()
method concatenates the first name and last name with a space in between.
Equals() Method
The Equals()
method is used to compare two strings for equality. It returns true
if the strings are equal, and false
otherwise.
Example: Using Equals() Method
string str1 = "Hello";
string str2 = "hello";
bool result = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine(result); // Output: True
In this example, Equals()
is used with StringComparison.OrdinalIgnoreCase
to compare the strings in a case-insensitive manner.
Substring() Method
The Substring()
method is used to extract a portion of a string starting at a specified index.
Example: Using Substring() Method
string str = "Hello, World!";
string subStr = str.Substring(7, 5);
Console.WriteLine(subStr); // Output: World
In this example, Substring()
extracts a substring starting at index 7 and spanning 5 characters.
Replace() Method
The Replace()
method is used to replace all occurrences of a specified string or character in a string with another specified string or character.
Example: Using Replace() Method
string str = "I love C#";
string newStr = str.Replace("C#", "programming");
Console.WriteLine(newStr); // Output: I love programming
In this example, the Replace()
method replaces "C#" with "programming" in the original string.
Split() Method
The Split()
method is used to split a string into an array of substrings based on a specified delimiter.
Example: Using Split() Method
string str = "apple,banana,orange";
string[] fruits = str.Split(',');
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
// Output:
// apple
// banana
// orange
In this example, the Split()
method splits the string at each comma, producing an array of fruit names.
Key Points to Remember
- The
Concat()
method concatenates multiple strings into one. - The
Equals()
method compares two strings for equality and supports case-insensitive comparisons. - The
Substring()
method extracts a portion of a string starting at a specified index. - The
Replace()
method replaces all occurrences of a substring or character in a string with another substring or character. - The
Split()
method divides a string into an array of substrings based on a specified delimiter.