C# - String Manipulation

String manipulation in C# refers to the process of modifying, combining, or extracting information from strings. It involves various operations such as concatenating (joining) strings, replacing text, converting cases (uppercase or lowercase), and more. String manipulation is essential for working with text data effectively in C#.

Here's a complete source code example of string manipulation in C#, along with the expected output:


using System;

class Program
{
    static void Main()
    {
        // Create a sample string
        string originalString = "Hello, World!";

        // Concatenate two strings
        string concatenatedString = originalString + " Welcome to C#";
        Console.WriteLine("Concatenated String: " + concatenatedString);

        // Find the length of the string
        int stringLength = originalString.Length;
        Console.WriteLine("String Length: " + stringLength);

        // Convert to uppercase
        string upperCaseString = originalString.ToUpper();
        Console.WriteLine("Uppercase: " + upperCaseString);

        // Replace a substring
        string replacedString = originalString.Replace("Hello", "Hi");
        Console.WriteLine("Replaced String: " + replacedString);

        // Check if it contains a substring
        bool containsSubstring = originalString.Contains("World");
        Console.WriteLine("Contains 'World': " + containsSubstring);

        // Split the string into an array
        string[] splitArray = originalString.Split(',');
        Console.WriteLine("Split String:");
        foreach (string part in splitArray)
        {
            Console.WriteLine(part.Trim()); // Trim removes leading/trailing spaces
        }
    }
}

In this example:

  1. We perform various string manipulations on the originalString variable, including concatenation, finding the length, converting to uppercase, replacing a substring, checking for substring existence, and splitting the string into an array.
  2. Each manipulation operation is explained in the comments, and the result is displayed using Console.WriteLine.

Here are some common string manipulation techniques in C#:

1. Concatenation:
Concatenation in C# refers to the process of combining or joining two or more strings together to create a new string. It's like linking or merging strings end-to-end to form a longer string. This operation is commonly used when you want to build longer text by combining shorter text fragments.


string firstName = "John";
string lastName = "Doe";

string fullName = firstName + " " + lastName; // Using the + operator
string greeting = string.Concat("Hello, ", firstName, " ", lastName); // Using string.Concat
string formattedGreeting = $"Hello, {firstName} {lastName}"; // Using string interpolation

2. Substring:
The 'Substring' method extracts a portion of a string based on a starting index and optional length.


string message = "Hello, World!";
string subMessage = message.Substring(7); // "World!"
string subMessageWithLength = message.Substring(7, 5); // "World"

3. ToLower and ToUpper:
The 'ToLower' and 'ToUpper' methods convert a string to lowercase or uppercase, respectively.


string message = "Hello, World!";
string lowerCaseMessage = message.ToLower(); // "hello, world!"
string upperCaseMessage = message.ToUpper(); // "HELLO, WORLD!"

3. Replace:
In C#, "string replace" refers to the process of finding and replacing a specific substring within a string with another substring. It allows you to change parts of a string while leaving the rest of it intact.


string message = "Hello, C# programming!";
string replacedMessage = message.Replace("C#", "C Sharp"); // "Hello, C Sharp programming!"

4. Split:
The 'Split' method divides a string into an array of substrings based on a specified delimiter.


string data = "apple,orange,banana";
string[] fruits = data.Split(','); // ["apple", "orange", "banana"]

5. Join:
The 'Join' method combines elements of an array into a single string using a specified separator.


string[] fruits = { "apple", "orange", "banana" };
string data = string.Join(",", fruits); // "apple,orange,banana"

5. Formatting:
String formatting allows you to create formatted strings using placeholders and arguments.


string name = "Alice";
int age = 30;

string formattedMessage = string.Format("Hello, {0}! You are {1} years old.", name, age);
string interpolatedMessage = $"Hello, {name}! You are {age} years old.";

6. Trim: The 'Trim', 'TrimStart', and 'TrimEnd' methods remove leading and trailing whitespace characters from a string.


string text = "   Hello, World!   ";
string trimmedText = text.Trim(); // "Hello, World!"
string leftTrimmedText = text.TrimStart(); // "Hello, World!   "
string rightTrimmedText = text.TrimEnd(); // "   Hello, World!"

7. Length:
The 'Length' property provides the count of characters within a string.


string message = "Hello, World!";
int length = message.Length; // 13

String manipulation is crucial for tasks like data validation, text processing, and formatting when working with textual data in C#. It allows you to transform and work with strings in ways that meet your application's specific requirements.