DevAcademia
C++C#CPythonJava
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction

Loading Cs tutorial…

Loading content
C# BasicsTopic 19 of 55
←PreviousPrevNextNext→

C# Strings - Complete Guide

Introduction to Strings in C#

Strings in C# are sequences of characters represented by the System.String class. Strings are immutable: once created, they cannot be modified, and any change results in a new string object.

C# provides rich string manipulation features such as concatenation, searching, formatting, splitting, and more. Mastering string handling is essential for most applications.

String Declaration and Initialization

Strings can be declared in multiple ways using the string keyword, the String class, var, or verbatim literals.

Example
using System;

namespace StringDeclarationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "Hello, World!";
            String str2 = "Hello, C#!";
            var str3 = "Hello, Var!";

            string empty1 = "";
            string empty2 = string.Empty;
            string nullString = null;

            string multiLine = @"This is a
multi-line
string example";

            Console.WriteLine(str1);
            Console.WriteLine(str2);
            Console.WriteLine(str3);
            Console.WriteLine($"Empty1: '{empty1}', Empty2: '{empty2}'");
            Console.WriteLine($"Null string: '{nullString}'");
            Console.WriteLine($"Multi-line:\n{multiLine}");

            Console.WriteLine($"Length of str1: {str1.Length}");
            Console.WriteLine($"Is str1 null or empty? {string.IsNullOrEmpty(str1)}");
            Console.WriteLine($"Is empty1 null or empty? {string.IsNullOrEmpty(empty1)}");
            Console.WriteLine($"Is nullString null or empty? {string.IsNullOrEmpty(nullString)}");
        }
    }
}
Output
Hello, World!
Hello, C#!
Hello, Var!
Empty1: '' , Empty2: ''
Null string: ''
Multi-line:
This is a
multi-line
string example
Length of str1: 13
Is str1 null or empty? False
Is empty1 null or empty? True
Is nullString null or empty? True

String Immutability

Strings are immutable in C#. Operations that look like they change a string actually create new instances.

Use StringBuilder when working with many string modifications to improve performance.

Example
using System;
using System.Text;

namespace StringImmutabilityExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string original = "Hello";
            string modified = original;

            Console.WriteLine($"Original: {original}");
            Console.WriteLine($"Modified: {modified}");
            Console.WriteLine($"ReferenceEquals? {object.ReferenceEquals(original, modified)}");

            modified += ", World!";
            Console.WriteLine($"After modification -> Original: {original}, Modified: {modified}");
            Console.WriteLine($"ReferenceEquals? {object.ReferenceEquals(original, modified)}");

            string str1 = "Hello";
            string str2 = "Hello";
            string str3 = new string("Hello".ToCharArray());

            Console.WriteLine($"str1 == str2: {str1 == str2}");
            Console.WriteLine($"str1 == str3: {str1 == str3}");
            Console.WriteLine($"ReferenceEquals(str1, str2): {object.ReferenceEquals(str1, str2)}");
            Console.WriteLine($"ReferenceEquals(str1, str3): {object.ReferenceEquals(str1, str3)}");

            StringBuilder sb = new StringBuilder();
            sb.Append("Hello");
            sb.Append(", World!");
            Console.WriteLine($"StringBuilder result: {sb.ToString()}");
        }
    }
}
Output
Original: Hello
Modified: Hello
ReferenceEquals? True
After modification -> Original: Hello, Modified: Hello, World!
ReferenceEquals? False
str1 == str2: True
str1 == str3: True
ReferenceEquals(str1, str2): True
ReferenceEquals(str1, str3): False
StringBuilder result: Hello, World!

Common String Methods

The String class provides many built-in methods for trimming, searching, modifying, and formatting strings.

Example
using System;

namespace StringMethodsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "   Hello, World!   ";
            Console.WriteLine($"Trimmed: '{text.Trim()}'");
            Console.WriteLine($"ToUpper: {text.ToUpper()}");
            Console.WriteLine($"ToLower: {text.ToLower()}");

            string sentence = "The quick brown fox jumps over the lazy dog";
            Console.WriteLine($"Contains 'fox'? {sentence.Contains("fox")}");
            Console.WriteLine($"StartsWith 'The'? {sentence.StartsWith("The")}");
            Console.WriteLine($"EndsWith 'dog'? {sentence.EndsWith("dog")}");
            Console.WriteLine($"IndexOf 'brown': {sentence.IndexOf("brown")}");

            Console.WriteLine($"Substring(10): {sentence.Substring(10)}");
            Console.WriteLine($"Replace 'fox' with 'cat': {sentence.Replace("fox", "cat")}");

            string[] words = sentence.Split(' ');
            Console.WriteLine("Split into words:");
            foreach (var w in words)
            {
                Console.WriteLine(w);
            }

            string joined = string.Join("-", words);
            Console.WriteLine($"Joined: {joined}");

            string formatted = string.Format("Hello, {0}! Today is {1:yyyy-MM-dd}", "Alice", DateTime.Now);
            Console.WriteLine(formatted);
        }
    }
}
Output
Trimmed: 'Hello, World!'
ToUpper:    HELLO, WORLD!   
ToLower:    hello, world!   
Contains 'fox'? True
StartsWith 'The'? True
EndsWith 'dog'? True
IndexOf 'brown': 10
Substring(10): brown fox jumps over the lazy dog
Replace 'fox' with 'cat': The quick brown cat jumps over the lazy dog
Split into words:
The
quick
brown
fox
jumps
over
the
lazy
dog
Joined: The-quick-brown-fox-jumps-over-the-lazy-dog
Hello, Alice! Today is 2023-10-15
Test your knowledge: C# Strings - Complete Guide
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
C# BasicsTopic 19 of 55
←PreviousPrevNextNext→