Welcome back! In this article, we’ll explore various string operations available in C#. Strings are an essential part of any programming language, and being able to manipulate them effectively is crucial. C# provides a rich set of methods and properties to work with strings. Let’s dive into some common string operations and see how to use them.
String Operations in C
- Concatenation
- Interpolation
- Substring
- IndexOf
- LastIndexOf
- Replace
- ToUpper and ToLower
- Trim
- Split
- Join
- Contains
- StartsWith and EndsWith
- Length
1. Concatenation
Concatenation is the process of combining two or more strings into one.
Example:
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // Output: John Doe
2. Interpolation
String interpolation is a way to create a new string by including variable values inside a string literal.
Example:
string firstName = "John";
string lastName = "Doe";
string fullName = $"{firstName} {lastName}";
Console.WriteLine(fullName); // Output: John Doe
3. Substring
The Substring
method extracts a portion of a string starting at a specified position.
Example:
string message = "Hello, World!";
string hello = message.Substring(0, 5);
Console.WriteLine(hello); // Output: Hello
4. IndexOf
The IndexOf
method returns the zero-based index of the first occurrence of a specified substring.
Example:
string message = "Hello, World!";
int index = message.IndexOf("World");
Console.WriteLine(index); // Output: 7
5. LastIndexOf
The LastIndexOf
method returns the zero-based index of the last occurrence of a specified substring.
Example:
string message = "Hello, World! Hello again!";
int index = message.LastIndexOf("Hello");
Console.WriteLine(index); // Output: 14
6. Replace
The Replace
method replaces all occurrences of a specified substring with another substring.
Example:
string message = "Hello, World!";
string newMessage = message.Replace("World", "C#");
Console.WriteLine(newMessage); // Output: Hello, C#!
7. ToUpper and ToLower
The ToUpper
method converts all characters in a string to uppercase, while ToLower
converts all characters to lowercase.
Example:
string message = "Hello, World!";
string upperMessage = message.ToUpper();
string lowerMessage = message.ToLower();
Console.WriteLine(upperMessage); // Output: HELLO, WORLD!
Console.WriteLine(lowerMessage); // Output: hello, world!
8. Trim
The Trim
method removes all leading and trailing white-space characters from a string.
Example:
string message = " Hello, World! ";
string trimmedMessage = message.Trim();
Console.WriteLine($"'{trimmedMessage}'"); // Output: 'Hello, World!'
9. Split
The Split
method splits a string into an array of substrings based on a specified delimiter.
Example:
string message = "Hello, World!";
string[] words = message.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
}
// Output:
// Hello,
// World!
10. Join
The Join
method concatenates an array of strings into a single string, with each element separated by a specified delimiter.
Example:
string[] words = { "Hello", "World" };
string message = string.Join(", ", words);
Console.WriteLine(message); // Output: Hello, World
11. Contains
The Contains
method checks whether a string contains a specified substring.
Example:
string message = "Hello, World!";
bool containsHello = message.Contains("Hello");
Console.WriteLine(containsHello); // Output: True
12. StartsWith and EndsWith
The StartsWith
method checks whether a string starts with a specified substring, and EndsWith
checks whether a string ends with a specified substring.
Example:
string message = "Hello, World!";
bool startsWithHello = message.StartsWith("Hello");
bool endsWithWorld = message.EndsWith("World!");
Console.WriteLine(startsWithHello); // Output: True
Console.WriteLine(endsWithWorld); // Output: True
13. Length
The Length
property returns the number of characters in a string.
Example:
string message = "Hello, World!";
int length = message.Length;
Console.WriteLine(length); // Output: 13
Example Program: Using Different String Operations
Here’s a simple program that demonstrates various string operations in C#:
using System;
class StringOperationsDemo
{
static void Main(string[] args)
{
// Concatenation
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine($"Full Name: {fullName}");
// Interpolation
string interpolatedName = $"{firstName} {lastName}";
Console.WriteLine($"Interpolated Name: {interpolatedName}");
// Substring
string message = "Hello, World!";
string hello = message.Substring(0, 5);
Console.WriteLine($"Substring: {hello}");
// IndexOf
int index = message.IndexOf("World");
Console.WriteLine($"Index of 'World': {index}");
// LastIndexOf
string repeatedMessage = "Hello, World! Hello again!";
int lastIndex = repeatedMessage.LastIndexOf("Hello");
Console.WriteLine($"Last Index of 'Hello': {lastIndex}");
// Replace
string newMessage = message.Replace("World", "C#");
Console.WriteLine($"Replaced Message: {newMessage}");
// ToUpper and ToLower
string upperMessage = message.ToUpper();
string lowerMessage = message.ToLower();
Console.WriteLine($"Uppercase: {upperMessage}");
Console.WriteLine($"Lowercase: {lowerMessage}");
// Trim
string paddedMessage = " Hello, World! ";
string trimmedMessage = paddedMessage.Trim();
Console.WriteLine($"Trimmed Message: '{trimmedMessage}'");
// Split
string[] words = message.Split(' ');
Console.WriteLine("Split Words:");
foreach (string word in words)
{
Console.WriteLine(word);
}
// Join
string joinedMessage = string.Join(", ", words);
Console.WriteLine($"Joined Message: {joinedMessage}");
// Contains
bool containsHello = message.Contains("Hello");
Console.WriteLine($"Contains 'Hello': {containsHello}");
// StartsWith and EndsWith
bool startsWithHello = message.StartsWith("Hello");
bool endsWithWorld = message.EndsWith("World!");
Console.WriteLine($"Starts with 'Hello': {startsWithHello}");
Console.WriteLine($"Ends with 'World!': {endsWithWorld}");
// Length
int length = message.Length;
Console.WriteLine($"Length: {length}");
}
}
Conclusion
C# provides a rich set of methods and properties for working with strings, allowing you to perform various operations such as concatenation, interpolation, substring extraction, searching, replacing, and more. By mastering these string operations, you can manipulate and process textual data effectively in your programs.
Practice using these string operations in your own projects to become more comfortable with their syntax and behavior. Stay tuned for more tutorials to further enhance your C# programming skills. Happy coding!