Working with text is one of the most common tasks in programming. Whether you’re reading user input, formatting output, or manipulating text files, understanding C# Strings is essential for writing efficient and clean code. In this detailed guide from Tpoint Tech, we’ll explore what strings are, how they work, and the most useful string methods in C#, along with practical examples that you can use in your own projects.
What Are C# Strings?
In C#, a string is a sequence of characters used to represent text. The C# Strings are immutable, meaning once a string is created, it cannot be changed. Any modification, such as concatenation or replacement, actually creates a new string in memory.
A simple example of a C# string:
string message = "Welcome to Tpoint Tech!";
Console.WriteLine(message);
Here, message
is a string variable that holds text data. You can use double quotes to create strings or use the @
symbol for verbatim strings that allow multi-line text.
Creating and Initializing Strings
You can create strings in several ways in C#:
string str1 = "Hello, World!";
string str2 = new string("Hello, Tpoint Tech!");
string str3 = @"C:\Users\TpointTech"; // Verbatim string
Each approach serves different use cases depending on how you want to handle escape sequences and formatting.
Common C# String Methods
C# provides a rich set of built-in string methods in the System.String
class. Let’s go through some of the most commonly used ones with examples.
1. Length Property
The Length
property returns the total number of characters in a string.
string name = "Tpoint Tech";
Console.WriteLine("Length: " + name.Length);
Output:
Length: 11
This property is useful when you need to loop through characters or validate user input.
2. ToUpper() and ToLower()
These methods convert a string to uppercase or lowercase.
string text = "Welcome to Tpoint Tech";
Console.WriteLine(text.ToUpper());
Console.WriteLine(text.ToLower());
Output:
WELCOME TO TPOINT TECH
welcome to tpoint tech
These methods are helpful in formatting data consistently, especially when comparing user input.
3. Trim(), TrimStart(), and TrimEnd()
These methods remove whitespace characters from the beginning and end of a string.
string text = " Learn C# Strings at Tpoint Tech! ";
Console.WriteLine(text.Trim());
Output:
Learn C# Strings at Tpoint Tech!
Using Trim()
ensures clean input data and prevents errors when processing strings.
4. Substring()
The Substring()
method extracts a portion of the string starting from a given index.
string topic = "C# Strings Tutorial";
string result = topic.Substring(3, 6);
Console.WriteLine(result);
Output:
Strings
This method is widely used in text parsing, such as extracting parts of URLs, file names, or codes.
5. Replace()
Replace()
substitutes all occurrences of a specified character or substring with another.
string text = "Welcome to Tpoint Tech!";
string newText = text.Replace("Tpoint", "CSharp");
Console.WriteLine(newText);
Output:
Welcome to CSharp Tech!
This is ideal for text formatting and sanitising user data.
6. Contains()
The Contains()
method checks if a specific substring exists within a string.
string sentence = "C# Strings are powerful.";
Console.WriteLine(sentence.Contains("powerful"));
Output:
True
This is very useful for conditional checks, such as validating keywords in text.
7. IndexOf() and LastIndexOf()
These methods find the position (index) of a character or substring within a string.
string text = "Learn C# Strings at Tpoint Tech";
Console.WriteLine(text.IndexOf("C#"));
Console.WriteLine(text.LastIndexOf("Tpoint"));
Output:
6
20
They are especially useful in parsing text or locating specific characters.
8. Split()
The Split()
method divides a string into an array based on a separator.
string names = "John,David,Steve,Emma";
string[] result = names.Split(',');
foreach (string name in result)
{
Console.WriteLine(name);
}
Output:
John
David
Steve
Emma
Splitting strings is essential when dealing with CSV data or formatted user input.
9. Join()
The Join()
method combines multiple strings into one, separated by a specified character.
string[] words = { "C#", "Strings", "Guide", "Tpoint", "Tech" };
string sentence = string.Join(" ", words);
Console.WriteLine(sentence);
Output:
C# Strings Guide Tpoint Tech
This is helpful when generating output from arrays or lists.
10. Equals() and Compare()
These methods are used to compare two strings for equality.
string a = "Tpoint";
string b = "tpoint";
Console.WriteLine(a.Equals(b)); // False (case-sensitive)
Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase)); // True
Compare()
works similarly but returns an integer indicating the relationship between the strings.
Conclusion
Mastering C# Strings is a fundamental skill every developer should acquire. From basic operations like trimming and replacing text to advanced techniques such as substring extraction and joining, C# provides a powerful set of tools for text manipulation.
At Tpoint Tech, we believe that understanding these string methods not only improves your coding efficiency but also helps you write cleaner and more maintainable applications. Practice using these methods in real-world projects, and soon you’ll be handling text data like a pro!
Whether you’re preparing for an interview or building enterprise applications, remember — strong string handling skills make strong C# developers.
Top comments (0)