DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: Basics of Strings

Meta Description: Explore the basics of string manipulation in C# with practical examples. Learn about concatenation, converting case, extracting substrings, and using built-in methods—all implemented in a simple Utilities class for easy understanding

Introduction:

Strings are a fundamental part of any programming language, and in C#, the string type is packed with a variety of built-in methods and properties that make manipulating text data easy and effective. In this article, we will explore some essential functionalities of the string type in C#, from properties like Length to common methods such as ToUpper(), Contains(), and different ways of concatenating strings. Let's dive into the powerful features C# offers for working with strings!


String Properties and Methods:

  1. Length Property:

One of the most basic things you can do with a string is determine its length using the Length property. The Length property returns the number of characters in the string. For example:

   string myString = "Hello, World!";
   int length = myString.Length;  // Returns 13
Enter fullscreen mode Exit fullscreen mode

Here, myString.Length returns 13, which represents the total number of characters in the string.

  1. ToUpper and ToLower Methods:

The ToUpper() and ToLower() methods are used to convert all the characters of a string to uppercase or lowercase, respectively. This is especially useful when you need case-insensitive comparison or formatting:

   string name = "John";
   string upperName = name.ToUpper();  // "JOHN"
   string lowerName = name.ToLower();  // "john"
Enter fullscreen mode Exit fullscreen mode
  1. Contains Method:

You can check if a string contains a specific substring using the Contains() method. This method returns true if the substring exists within the string, and false otherwise:

   string greeting = "Hello, World!";
   bool containsHello = greeting.Contains("Hello");  // Returns true
Enter fullscreen mode Exit fullscreen mode

The Contains() method helps you determine if a particular word or sequence of characters exists in a given string.

  1. Replace Method:

If you need to replace parts of a string with something else, you can use the Replace() method. For example:

   string text = "I like apples.";
   string newText = text.Replace("apples", "oranges");  // "I like oranges."
Enter fullscreen mode Exit fullscreen mode

Here, we replaced the word "apples" with "oranges" in the string.

  1. Substring Method:

The Substring() method is used to extract a portion of the string, starting at a specific index and optionally for a specified length:

   string word = "Bethany";
   string sub = word.Substring(1, 3);  // Returns "eth"
Enter fullscreen mode Exit fullscreen mode

In this example, we start at index 1 (which refers to the second character) and take 3 characters, resulting in "eth".

Concatenating Strings:

String concatenation involves combining multiple strings into one. In C#, there are a few ways to do this:

  1. Using the + Operator:

The simplest way to concatenate strings is by using the + operator:

   string firstName = "John";
   string lastName = "Doe";
   string fullName = firstName + " " + lastName;  // "John Doe"
Enter fullscreen mode Exit fullscreen mode

Here, we added a space between firstName and lastName to create the fullName.

  1. Using String.Concat():

Another option is to use the String.Concat() method, which is especially useful if you have multiple strings to concatenate:

   string fullName = String.Concat(firstName, " ", lastName);  // "John Doe"
Enter fullscreen mode Exit fullscreen mode

String Interpolation:

String interpolation is a more elegant way to concatenate strings, and it's considered the preferred method for readability. You use the $ symbol before the string and include variables within curly braces {}:

string firstName = "John";
string lastName = "Doe";
string fullName = $"{firstName} {lastName}";  // "John Doe"
Enter fullscreen mode Exit fullscreen mode

This approach makes your code more readable, as you don’t need to worry about managing + operators and ensuring proper spacing.

Method Chaining:

C# allows chaining methods for convenience. For example, you can call multiple string methods one after the other:

string empId = $"{firstName.Trim().ToLower()}-{lastName.Trim().ToLower()}";
Enter fullscreen mode Exit fullscreen mode

In this example, we remove any leading or trailing spaces from firstName and lastName using Trim(), convert them to lowercase with ToLower(), and concatenate them with a dash (-).

Putting It All Together in the Utilities Class:

To bring all these concepts together, let's create a method called ManipulatingStrings in our Utilities class. This method will demonstrate various string manipulations that we've discussed:

public class Utilities
{
    public void ManipulatingStrings()
    {
        string firstName = "John";
        string lastName = " Doe ";

        // Concatenate using +
        string fullName = firstName + " " + lastName.Trim();
        Console.WriteLine($"Full Name: {fullName}");

        // Concatenate using String.Concat
        string employeeIdentification = String.Concat(firstName, lastName.Trim());
        Console.WriteLine($"Employee Identification: {employeeIdentification}");

        // Convert to lowercase and concatenate
        string empId = $"{firstName.ToLower()}-{lastName.Trim().ToLower()}";
        Console.WriteLine($"Employee ID: {empId}");

        // Check if fullName contains a substring
        bool containsJohn = fullName.Contains("John");
        Console.WriteLine($"Contains 'John': {containsJohn}");

        // Extract substring
        string part = fullName.Substring(1, 3);
        Console.WriteLine($"Substring: {part}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Here’s how you can use the ManipulatingStrings method from your Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        Utilities utilities = new Utilities();
        utilities.ManipulatingStrings();

        Console.ReadLine(); // To keep the console open
    }
}
Enter fullscreen mode Exit fullscreen mode

This will allow you to observe how each string manipulation method works. The Utilities class now serves as a helper class that demonstrates different ways you can handle and manipulate strings in C#.

Conclusion:

Strings are powerful in C#, offering a wide range of methods and properties for manipulating text. From determining length to converting case, checking contents, and concatenating strings in different ways, there are many functionalities at your disposal. Understanding these basics will make working with text in C# much easier. So, why not try it out in Visual Studio and see these methods in action?

Top comments (0)