String Manipulation in C#
Introduction
Strings are a sequence of characters and are one of the most used data types in programming. In C#, strings are represented by the string
class and are immutable. This means that once a string is created, it cannot be changed. Instead, any modifications to a string result in the creation of a new string.
Creating Strings
Strings can be created in various ways in C#. Here are some examples:
string str2 = new string('a', 5); // Creates a string with 5 'a' characters
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
string str3 = new string(charArray);
Concatenation
Concatenation is the process of combining two or more strings. In C#, this can be done using the +
operator or the String.Concat
method.
string str2 = "World";
string result = str1 + ", " + str2 + "!"; // Using + operator
string result2 = String.Concat(str1, ", ", str2, "!"); // Using String.Concat method
String Interpolation
String interpolation is a feature that allows the embedding of expressions inside string literals. It is done using the $
symbol before the string.
int age = 30;
string result = $"My name is {name} and I am {age} years old.";
Accessing Characters
You can access individual characters in a string using an indexer. The index is zero-based.
char firstChar = str[0]; // 'H'
char lastChar = str[str.Length - 1]; // 'o'
Substring
The Substring
method is used to extract a portion of the string starting from a specified index.
string substr = str.Substring(7, 5); // "World"
Replacing Characters
The Replace
method is used to replace all occurrences of a specified character or substring with another character or substring.
string result = str.Replace("World", "C#"); // "Hello, C#!"
Splitting Strings
The Split
method is used to split a string into an array of substrings based on specified delimiters.
string[] fruits = str.Split(','); // ["apple", "banana", "cherry"]
Trimming Strings
The Trim
method is used to remove all leading and trailing white-space characters from the string. You can also use TrimStart
and TrimEnd
for specific trimming.
string trimmedStr = str.Trim(); // "Hello, World!"
String Case Conversion
C# provides methods to convert strings to uppercase or lowercase.
string upperStr = str.ToUpper(); // "HELLO, WORLD!"
string lowerStr = str.ToLower(); // "hello, world!"
Checking for Substring
The Contains
method checks if a specified substring exists within the string.
bool containsWorld = str.Contains("World"); // true
String Length
The Length
property returns the number of characters in the string.
int length = str.Length; // 13
Conclusion
String manipulation is a fundamental skill in C# programming. This tutorial covered the basics of creating, concatenating, and modifying strings, extracting substrings, and other common operations. With these techniques, you can handle most string-related tasks in your C# programs.