Exploring String Manipulation in C#: A Comprehensive Guide
Introduction:
Working
with strings is a fundamental aspect of any programming language, including C#.
In this article, we will delve into various techniques and methods for
efficient string manipulation in C#. By understanding these concepts, you'll be
able to handle strings effectively and optimize your code for better
performance.
Keyword: C# string manipulation, string
handling in C#, working with strings in C#, string methods in C#
1. String Basics:
First,
let's start with the basics. In C#, a string is a sequence of characters
enclosed within double quotes (" "). We'll explore how to declare and
initialize strings, concatenate them, and access individual characters within a
string.
Code Example:
string message = "Hello, ";
string name = "John";
string greeting = message + name;
char firstCharacter = name[0];
Console.WriteLine(greeting); // Output: Hello, John
Console.WriteLine(firstCharacter); // Output: J
2. String Methods and Properties:
string text = "Hello, World!";
int length = text.Length;
string upperCase = text.ToUpper();
string lowerCase = text.ToLower();
string substring = text.Substring(7);
string replacedText = text.Replace("World", "Universe");
string trimmedText = text.Trim();
string[] words = text.Split(' ');
bool contains = text.Contains("Hello");
Console.WriteLine(length); // Output: 13
Console.WriteLine(upperCase); // Output: HELLO, WORLD!
Console.WriteLine(lowerCase); // Output: hello, world!
Console.WriteLine(substring); // Output: World!
Console.WriteLine(replacedText); // Output: Hello, Universe!
Console.WriteLine(trimmedText); // Output: Hello, World!
Console.WriteLine(words[0]); // Output: Hello,
Console.WriteLine(contains); // Output: True
3. String Formatting:
string name = "Alice";
int age = 30;
double salary = 5000.50;
string formattedString = String.Format("Name: {0}, Age: {1}, Salary: {2:C}", name, age, salary);
string compositeFormattedString = String.Format("Name: {0}, Age: {1}, Salary: {2}", name, age, salary);
string interpolatedString = $"Name: {name}, Age: {age}, Salary: {salary:C}";
Console.WriteLine(formattedString);
Console.WriteLine(compositeFormattedString);
Console.WriteLine(interpolatedString);
4. StringBuilder Class:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Hello");
stringBuilder.Append(", ");
stringBuilder.Append("World!");
string finalString = stringBuilder.ToString();
Console.WriteLine(finalString); // Output: Hello, World!
Conclusion:
0 Comments