Strings are fundamental in almost every programming task. In C#, the string class represents text as a sequence of Unicode characters. This tutorial will provide an overview of working with strings in C#.
string name = "Alice"; string greeting = "Hello, world!";
Length: Returns the number of characters in the string.
int length = name.Length; // Outputs: 5
Concatenation: You can concatenate strings using the + operator.
string fullName = "Alice" + " " + "Brown";
Or use the string.Concat() method:
string fullName = string.Concat("Alice", " ", "Brown"); Substring: Extract a substring from a string.
string part = greeting.Substring(7, 5); // Outputs: "world"
Replace: Replace occurrences of a specified substring.
string newGreeting = greeting.Replace("world", "Alice"); // Outputs: "Hello, Alice!" ToLower and ToUpper: Convert to lowercase or uppercase.
string upper = name.ToUpper(); // Outputs: "ALICE" string lower = name.ToLower(); // Outputs: "alice"
Introduced in C# 6, string interpolation provides a more readable and convenient syntax to embed expression values directly into string literals.
int age = 25; string interpolated = $"My name is {name} and I am {age} years old."; To check if a string is null or empty:
if (string.IsNullOrEmpty(name)) { Console.WriteLine("Name is not set."); } To also check for whitespace:
if (string.IsNullOrWhiteSpace(name)) { Console.WriteLine("Name is not set or is just whitespace."); } When comparing strings, it's essential to know if you want a case-sensitive or case-insensitive comparison.
bool areEqualCaseSensitive = string.Equals("Alice", "alice"); // Outputs: false bool areEqualCaseInsensitive = string.Equals("Alice", "alice", StringComparison.OrdinalIgnoreCase); // Outputs: true Split:
string data = "apple,banana,cherry"; string[] fruits = data.Split(','); Join:
string[] words = { "Hello", "world!" }; string sentence = string.Join(" ", words); // Outputs: "Hello world!" Use the @ symbol for verbatim strings, which don't treat backslashes as escape characters.
string filePath = @"C:\Documents\Report.txt";
For scenarios where you need to manipulate strings extensively (like in loops), the StringBuilder class is more efficient than using regular strings because strings are immutable.
StringBuilder sb = new StringBuilder(); sb.Append("Hello"); sb.AppendLine("World"); string result = sb.ToString(); // Outputs: "Hello\nWorld\n" This tutorial provides a basic overview of working with strings in C#. The string class in C# is versatile and equipped with many methods and properties to simplify various text-processing tasks. Familiarizing oneself with these features will be beneficial for many programming scenarios.
css-float height manytomanyfield api-platform.com cancellation-token jackson2 yum kendo-listview webdav xcodebuild