C# Strings

Welcome to The Coding College! In this tutorial, we’ll dive deep into C# Strings, an essential concept for handling and manipulating text data in C#. Strings are widely used in programming, and mastering them will greatly enhance your coding skills.

Learn more tutorials at thecodingcollege.com to advance your programming knowledge!

What is a String in C#?

A string in C# is a sequence of characters enclosed within double quotes (" "). Strings are immutable, meaning once created, they cannot be changed. However, C# provides many methods to manipulate strings efficiently.

In C#, strings belong to the System.String class, and you can perform various operations like concatenation, comparison, splitting, and more.

Declaring Strings in C#

Here’s how you can declare and initialize strings in C#:

using System;

class Program
{
    static void Main()
    {
        string greeting = "Hello, World!";
        Console.WriteLine(greeting);
    }
}

// Output:
// Hello, World!

String Concatenation

String concatenation combines two or more strings into one.

Using the + Operator

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

Console.WriteLine(fullName);  // Output: John Doe

Using String.Concat() Method

string fullName = String.Concat("John", " ", "Doe");
Console.WriteLine(fullName);  // Output: John Doe

Using String Interpolation (Recommended)

String interpolation is a modern and cleaner way to concatenate strings using $.

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

string fullName = $"My name is {firstName} {lastName}.";
Console.WriteLine(fullName);  // Output: My name is John Doe.

Common String Methods in C#

The String class in C# provides several built-in methods for manipulating strings:

MethodDescriptionExampleResult
string.LengthReturns the length of the string."Hello".Length5
string.ToUpper()Converts the string to uppercase."hello".ToUpper()HELLO
string.ToLower()Converts the string to lowercase."HELLO".ToLower()hello
string.Trim()Removes whitespace from the start and end." Hello ".Trim()Hello
string.Substring(x, y)Extracts a portion of the string."Hello".Substring(0, 2)He
string.Replace(old, new)Replaces characters or substrings."hello".Replace("e", "a")hallo
string.Contains()Checks if a string contains a specified substring."hello".Contains("ell")True
string.IndexOf()Returns the position of a substring or character."hello".IndexOf("e")1
string.Split()Splits a string into an array based on a separator."A,B,C".Split(',')A B C
string.Equals()Checks if two strings are equal."hello".Equals("hello")True

String Examples

1. String Length and Case Conversion

using System;

class StringExample
{
    static void Main()
    {
        string text = "Hello, C#";

        Console.WriteLine("Length of string: " + text.Length);
        Console.WriteLine("Uppercase: " + text.ToUpper());
        Console.WriteLine("Lowercase: " + text.ToLower());
    }
}

// Output:
// Length of string: 9
// Uppercase: HELLO, C#
// Lowercase: hello, c#

2. Substring and Replace

using System;

class StringExample
{
    static void Main()
    {
        string text = "Welcome to C# Programming";

        Console.WriteLine("Substring: " + text.Substring(11, 2));  // Output: C#
        Console.WriteLine("Replace: " + text.Replace("C#", "Java"));  // Output: Welcome to Java Programming
    }
}

3. Checking Substrings and Splitting Strings

using System;

class StringExample
{
    static void Main()
    {
        string text = "Apple, Banana, Cherry";

        // Check if text contains "Banana"
        Console.WriteLine("Contains Banana: " + text.Contains("Banana"));

        // Split the string
        string[] fruits = text.Split(',');
        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit.Trim());
        }
    }
}

// Output:
// Contains Banana: True
// Apple
// Banana
// Cherry

String Immutability in C#

Strings in C# are immutable, meaning once you create a string, you cannot change its content. Instead, operations like concatenation or replacement create new string objects.

Example:

string str = "Hello";
str = str + " World";

Console.WriteLine(str);  // Output: Hello World

Here, the original str is not modified; a new string is created.

Use StringBuilder for Efficiency

If you perform many string operations (like concatenations in a loop), use the StringBuilder class for better performance.

using System.Text;

class Program
{
    static void Main()
    {
        StringBuilder sb = new StringBuilder();

        for (int i = 1; i <= 5; i++)
        {
            sb.Append("Number: " + i + "\n");
        }

        Console.WriteLine(sb.ToString());
    }
}

// Output:
// Number: 1
// Number: 2
// Number: 3
// Number: 4
// Number: 5

Benefits of C# Strings

  1. Simple to Use: Intuitive and beginner-friendly.
  2. Versatile: Offers powerful methods for manipulation.
  3. Efficient: Use StringBuilder for large string operations.
  4. Standardized: Works seamlessly with .NET libraries and tools.

Conclusion

Strings are an essential part of C# programming, and understanding their methods and behavior will help you write cleaner and more efficient code. Use string methods wisely and leverage StringBuilder for optimal performance in complex operations.

For more tutorials on C# and other programming languages, visit thecodingcollege.com!

Leave a Comment