C# String Methods

C# provides a wide range of methods to manipulate strings. These methods allow you to modify, search, and format strings effectively.

Key Topics

1. Substring Method

Extracts a substring starting from a specified index and optional length.

Example: Using Substring

string text = "Hello, World!";
string subText = text.Substring(7, 5);
Console.WriteLine(subText);  // Outputs: World

2. ToUpper and ToLower

Converts all characters in the string to uppercase or lowercase.

Example: Converting Case

string name = "John Doe";
Console.WriteLine(name.ToUpper()); // Outputs: JOHN DOE
Console.WriteLine(name.ToLower()); // Outputs: john doe

3. Trim Method

Removes leading and trailing whitespace characters from the string.

Example: Trimming Whitespace

string message = "   Hello, World!   ";
Console.WriteLine($"'{message}'");         // Outputs: '   Hello, World!   '
Console.WriteLine($"'{message.Trim()}'"); // Outputs: 'Hello, World!'

4. Replace Method

Replaces all occurrences of a specified string with another string.

Example: Replacing Substrings

string text = "I love apples";
string newText = text.Replace("apples", "oranges");
Console.WriteLine(newText); // Outputs: I love oranges

5. Contains Method

Checks if the string contains a specified substring.

Example: Checking for Substrings

string sentence = "The quick brown fox jumps over the lazy dog.";
bool hasFox = sentence.Contains("fox");
Console.WriteLine(hasFox); // Outputs: True

6. IndexOf Method

Returns the zero-based index of the first occurrence of a specified substring.

Example: Finding the Position of a Substring

string phrase = "Find the needle in the haystack.";
int index = phrase.IndexOf("needle");
Console.WriteLine(index); // Outputs: 9

Key Takeaways

  • String methods provide powerful ways to manipulate and analyze text.
  • Methods like Substring, Replace, and IndexOf are essential for string manipulation.
  • Understanding these methods enhances your ability to process and modify strings effectively.