Mastering String Manipulations in C#
2 min read · — #csharp-interview#junior#strings#string-literals
Welcome to this guide on string manipulations in C#. As a fundamental building block in programming, strings are versatile data structures that allow for a myriad of operations. Whether you're prepping for a technical interview, brushing up on your coding skills, or diving into C# for the first time, understanding the intricacies of strings is paramount. In this post, we'll explore some of the most common operations and techniques you'll encounter when working with strings in C#. Let's dive in!
1. Declaring and Initializing Strings:
In C#, you can declare a string using the string
keyword.
string greeting = "Hello, Universe!";
2. Concatenation:
Strings can be joined together using the +
operator or the string.Concat
method.
string firstName = "Jane";
string lastName = "Smith";
string fullName = firstName + " " + lastName; // "Jane Smith"
3. Length of a String:
The Length
property can be used to get the number of characters in a string.
string word = "Programming";
int wordLength = word.Length; // wordLength will be 11
4. Substrings:
You can extract a part of a string using the Substring
method.
string text = "Universe";
string part = text.Substring(1, 4); // "nive"
5. Replacing Parts of a String:
Use the Replace
method to replace portions of a string.
string sentence = "I enjoy coding.";
// "I enjoy reading."
string newSentence = sentence.Replace("coding", "reading");
6. Checking for Substring Presence:
To check if a string contains another string, use the Contains
method.
string message = "Welcome to the C# tutorial.";
bool containsWord = message.Contains("tutorial"); // true
7. Conversion to Upper or Lower Case:
Strings can be converted to upper or lower case using the ToUpper
and ToLower
methods respectively.
string lowerCase = "universe";
string upperCase = lowerCase.ToUpper(); // "UNIVERSE"
8. Splitting a String:
To split a string based on certain characters or strings, use the Split method.
string data = "earth,mars,venus";
string[] planets = data.Split(','); // { "earth", "mars", "venus" }
9. Trimming Strings:
To remove whitespace (or other characters) from the beginning and end of a string, use the Trim
method.
string padded = " Space String ";
string trimmed = padded.Trim(); // "Space String"
10. Comparing Strings:
Strings can be compared using the Equals
method or the ==
operator.
string a = "world";
string b = "WORLD";
bool areEqual = a.Equals(b, StringComparison.OrdinalIgnoreCase); // true
Conclusion
Understanding and mastering these string operations will set you up for success in any technical interview that delves into your C# expertise. Remember, the examples here provide a solid foundation, but there's always more to explore. Keep practicing and diving deeper into the world of strings in C#.
Best wishes in your interview preparations!