C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# String

In C#, the string class represents a sequence of characters. It is an object of the System.String class, and is one of the most commonly used data types. In this tutorial, we'll cover the basics of working with strings in C#.

  • Creating strings

To create a string, use double quotes ("") and assign it to a variable:

string myString = "Hello, world!";
  • String concatenation

To concatenate strings, use the '+' operator:

string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // "John Doe"
  • Interpolation

C# supports string interpolation, which allows you to embed expressions within string literals:

string name = "John";
int age = 30;
string info = $"My name is {name} and I am {age} years old."; // "My name is John and I am 30 years old."
  • Escape sequences

Escape sequences are used to represent special characters in a string:

  • \" �C Double quote
  • \\ �C Backslash
  • \n �C New line
  • \t �C Tab
string message = "This is a line with a \"quote\" and a \\backslash."; // "This is a line with a "quote" and a \backslash."
  • String methods

C# provides many useful string methods, such as:

  • ToUpper(): Convert the string to uppercase
  • ToLower(): Convert the string to lowercase
  • Trim(): Remove whitespace from the beginning and end of the string
  • Substring(): Extract a portion of the string
  • IndexOf(): Find the index of a character or substring
  • Replace(): Replace all occurrences of a substring with another substring
string original = " Hello, World! ";
string upper = original.ToUpper(); // " HELLO, WORLD! "
string lower = original.ToLower(); // " hello, world! "
string trimmed = original.Trim(); // "Hello, World!"
string substring = original.Substring(0, 5); // " Hello"
int index = original.IndexOf('W'); // 8
string replaced = original.Replace("World", "C#"); // " Hello, C#! "
  • Comparing strings

Use the == operator to compare strings for equality, and the != operator to check for inequality:

string str1 = "hello";
string str2 = "world";
bool areEqual = str1 == str2; // false
bool areNotEqual = str1 != str2; // true

To compare strings case-insensitively, use the String.Equals() method:

string str1 = "Hello";
string str2 = "hello";
bool areEqual = String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase); // true

This tutorial is just the beginning of your journey with strings in C#. There are many more methods and features available in the System.String class, so be sure to explore the official documentation for more information.

  1. How to use strings in C#

    Strings are sequences of characters and are widely used in C# for text manipulation.

    string greeting = "Hello, C# strings!";
    
  2. String manipulation in C#

    Perform various string manipulations, like changing case and reversing.

    string original = "C#";
    string manipulated = original.ToLower(); // Change to lowercase
    
  3. Concatenating strings in C#

    Combine strings using the + operator or String.Concat method.

    string firstName = "John";
    string lastName = "Doe";
    string fullName = firstName + " " + lastName; // Concatenation
    
  4. String interpolation in C#

    Use string interpolation for more readable and expressive string formatting.

    string result = $"{firstName} {lastName}"; // Interpolation
    
  5. Working with string literals in C#

    String literals are constant values embedded directly in the code.

    string literal = "This is a string literal";
    
  6. Substring operations in C# strings

    Extract substrings using Substring method.

    string text = "C# Programming";
    string substring = text.Substring(2, 5); // Extract " Programming"
    
  7. Searching and replacing in C# strings

    Use IndexOf, LastIndexOf, Replace for searching and replacing.

    string sentence = "C# is awesome!";
    int index = sentence.IndexOf("awesome"); // Find index
    string replaced = sentence.Replace("awesome", "fantastic"); // Replace
    
  8. String comparison in C#

    Compare strings using methods like Equals, Compare, and operators.

    string str1 = "C#";
    string str2 = "c#";
    bool areEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase); // Case-insensitive comparison
    
  9. String formatting in C#

    Format strings using String.Format or interpolated strings.

    int age = 25;
    string formatted = String.Format("My age is {0}", age);
    
  10. Common string methods in C#

    Explore common string methods like ToUpper, ToLower, Trim, etc.

    string text = "   C# is fun!   ";
    string trimmed = text.Trim(); // Remove leading and trailing whitespaces
    
  11. StringBuilder vs. String concatenation in C#

    Use StringBuilder for efficient string concatenation in loops.

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < 1000; i++)
    {
        builder.Append(i.ToString());
    }
    string result = builder.ToString();
    
  12. Unicode and character encoding in C# strings

    Strings in C# are Unicode by default, supporting a wide range of characters.

    string unicodeString = "C# and Unicode ❤";
    
  13. Handling null and empty strings in C#

    Check for null or empty strings before performing operations.

    string userInput = GetUserInput();
    if (!string.IsNullOrEmpty(userInput))
    {
        // Perform operations
    }