You are currently viewing Mastering C# String Functions: A Comprehensive Guide with Examples

Mastering C# String Functions: A Comprehensive Guide with Examples

Introduction to C# String Functions

C# provides a rich set of string manipulation functions that allow developers to work efficiently with text data. Whether you need to search for substrings, manipulate case, or format strings, C# has you covered. In this tutorial, we’ll explore some of the most commonly used C# string functions with clear examples to illustrate their usage.

1. Length: Finding the Length of a String

The Length property in C# returns the number of characters in a string.

string str = "Hello, World!";
int length = str.Length;
Console.WriteLine("Length of the string: " + length); // Output: 13

2. Substring: Extracting a Portion of a String

The Substring method enables you to extract a substring from a given string based on the specified start index and optional length.

string str = "Hello, World!";
string substr = str.Substring(7, 5);
Console.WriteLine("Substring: " + substr); // Output: "World"

3. ToUpper and ToLower: Changing Case

The ToUpper and ToLower methods convert all characters in a string to uppercase and lowercase, respectively.

string str = "Hello, World!";
string upper = str.ToUpper();
string lower = str.ToLower();
Console.WriteLine("Uppercase: " + upper); // Output: "HELLO, WORLD!"
Console.WriteLine("Lowercase: " + lower); // Output: "hello, world!"

4. Concatenation: Combining Strings

You can concatenate strings using the + operator or the Concat method.

string str1 = "Hello";
string str2 = "World";
string combined = str1 + ", " + str2 + "!";
Console.WriteLine("Concatenated string: " + combined); // Output: "Hello, World!"

5. Replace: Replacing Substrings

The Replace method substitutes all occurrences of a specified string or character in a string with another string.

string str = "Hello, World!";
string replaced = str.Replace("Hello", "Hi");
Console.WriteLine("Replaced string: " + replaced); // Output: "Hi, World!"


Mastering C# string functions is essential for effective text processing and manipulation in your applications. By understanding and utilizing these functions, you can write cleaner and more efficient code. Experiment with these examples and explore additional string functions to unlock the full potential of C# string manipulation capabilities.

Leave a Reply