String Methods in C#
String Methods in C#
C# provides a rich set of methods to manipulate strings, making it easy to perform various operations like searching, replacing, formatting, and more. Here are some of the most commonly used string methods:
Basic String Operations
Length: Returns the number of characters in the string.
C#
string str = "Hello, World!"; int length = str.Length; // length = 13
ToUpper() and ToLower(): Converts the string to uppercase or lowercase.
C#
string str = "hello, world!"; string upper = str.ToUpper(); // upper = "HELLO, WORLD!" string lower = str.ToLower(); // lower = "hello, world!"
Trim(): Removes leading and trailing whitespace.
C#
string str = " Hello, World! "; string trimmed = str.Trim(); // trimmed = "Hello, World!"
Substring(): Extracts a substring from the string.
C#
string str = "Hello, World!"; string substring = str.Substring(7, 5); // substring = "World"
Searching and Replacing
IndexOf() and LastIndexOf(): Finds the index of a specified character or substring.
C#
string str = "Hello, World!"; int index = str.IndexOf('o'); // index = 4 int lastIndex = str.LastIndexOf('o'); // lastIndex = 7
Contains(): Checks if a string contains a specific substring.
C#
string str = "Hello, World!"; bool containsWorld = str.Contains("World"); // containsWorld = true
Replace(): Replaces all occurrences of a specified substring with another substring.
C#
string str = "Hello, World!"; string replaced = str.Replace("World", "Universe"); // replaced = "Hello, Universe!"
Formatting and Parsing
Format(): Formats a string using placeholders.
C#
string name = "Alice"; int age = 30; string formatted = string.Format("Name: {0}, Age: {1}", name, age);
Parse(): Converts a string to a numeric type.
C#
string str = "123"; int number = int.Parse(str);
Other Useful Methods
Split(): Splits a string into an array of substrings based on a delimiter.
Join(): Joins an array of strings into a single string.
StartsWith() and EndsWith(): Checks if a string starts or ends with a specific substring.
IsNullOrEmpty(): Checks if a string is null or empty.
By mastering these string methods, you can effectively manipulate and process text data in your C# applications.
Would you like to explore a specific string method or a practical example?
Comments
Post a Comment