Master C# Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Strings in C#

A string is a sequence of characters used to store and manipulate text. Strings are one of the most commonly used data types in C# and .NET applications.

Simple Definition: A string is used to store text such as names, addresses, email IDs, messages, usernames, and descriptions.

Creating a String

In C#, the string keyword is used to declare a string variable. String values are written inside double quotation marks.

C#
using System;
 
string name = "Rahul";

Console.WriteLine(name);
Output
Rahul

String Declaration

A string can first be declared and then assigned a value.

C#
using System;
 
string firstName;

firstName = "Amit";

Console.WriteLine(firstName);
Output
Amit

String Concatenation

String concatenation means joining two or more strings together. The + operator can be used for concatenation.

C#
using System;
 
string firstName = "Rahul";
string lastName = "Patil";

string fullName = firstName + " " + lastName;

Console.WriteLine(fullName);
Output
Rahul Patil

String Interpolation

String interpolation provides a clean and readable way to insert variables into a string. It uses the $ symbol.

C#
using System;
 
string name = "Sneha";
int age = 22;

Console.WriteLine($"My name is {name} and my age is {age}.");
Output
My name is Sneha and my age is 22.

Accessing Characters

Individual characters of a string can be accessed using an index. String indexing starts from 0.

C#
using System;

class Program
{
    static void Main()
    {
        string name = "CIIT";

        Console.WriteLine("Character 1: " + name[0]);
        Console.WriteLine("Character 2: " + name[1]);
        Console.WriteLine("Character 3: " + name[2]);
        Console.WriteLine("Character 4: " + name[3]);
    }
}
Output
Character 1: C
Character 2: I
Character 3: I
Character 4: T
Important: String indexing starts from 0. In the string "CIIT", C is at index 0 and T is at index 3.

String Length

The Length property returns the total number of characters in a string.

C#
using System;
 
string text = "Hello";

Console.WriteLine(text.Length);
Output
5

ToUpper()

The ToUpper() method converts all characters in a string to uppercase.

C#
using System;
 
string text = "ciit training";

Console.WriteLine(text.ToUpper());
Output
CIIT TRAINING

ToLower()

The ToLower() method converts all characters in a string to lowercase.

C#
using System;
 
string text = "CIIT TRAINING";

Console.WriteLine(text.ToLower());
Output
ciit training

Trim()

The Trim() method removes whitespace from the beginning and end of a string.

C#
using System;
 
string name = "   Rahul   ";

Console.WriteLine(name.Trim());
Output
Rahul

Contains()

The Contains() method checks whether a specified value exists inside a string. It returns true or false.

C#
using System;
string message = "Welcome to CIIT Training Institute";

Console.WriteLine(message.Contains("CIIT"));
Output
True

StartsWith()

The StartsWith() method checks whether a string starts with a specified value.

C#
using System;
 
string name = "Rahul";

Console.WriteLine(name.StartsWith("Rah"));
Output
True

EndsWith()

The EndsWith() method checks whether a string ends with a specified value.

C#
using System;
 
string email = "student@gmail.com";

Console.WriteLine(email.EndsWith(".com"));
Output
True

Replace()

The Replace() method replaces a specified value with another value.

C#
using System;
 
string message = "Hello Java";

string result = message.Replace("Java", "C#");

Console.WriteLine(result);
Output
Hello C#

Substring()

The Substring() method extracts a portion of a string.

C#
using System;
 
string text = "Hello World";

string result = text.Substring(0, 5);

Console.WriteLine(result);
Output
Hello

Split()

The Split() method divides a string into multiple parts based on a specified separator.

C#
using System;
 
string data = "Java,C#,Python";

string[] languages = data.Split(',');

foreach (string language in languages)
{
    Console.WriteLine(language);
}
Output
Java
C#
Python

String Comparison

Strings can be compared using the == operator.

C#
using System;
 
string username1 = "admin";
string username2 = "admin";

if (username1 == username2)
{
    Console.WriteLine("Both strings are same");
}
else
{
    Console.WriteLine("Strings are different");
}
Output
Both strings are same

String Immutability

Strings in C# are immutable. This means that once a string object is created, its value cannot be changed directly. String operations create a new string.

C#
using System;
 
string text = "Hello";

text = text + " World";

Console.WriteLine(text);
Output
Hello World

Common String Methods

Method / Property Purpose
Length Returns the number of characters
ToUpper() Converts text to uppercase
ToLower() Converts text to lowercase
Trim() Removes leading and trailing spaces
Contains() Checks whether text exists
StartsWith() Checks the beginning of a string
EndsWith() Checks the end of a string
Replace() Replaces specified text
Substring() Extracts part of a string
Split() Splits a string into multiple parts

Example 🌍❤️

String operations are commonly used in login systems, registration forms, search functionality and data validation.

C#
using System;
 
string email = "  student@gmail.com  ";

email = email.Trim();

if (email.EndsWith("@gmail.com"))
{   
    Console.WriteLine("Valid Gmail Address");
}
else
{
    Console.WriteLine("Invalid Email Address");
}
Output
Valid Gmail Address
CIIT Practical Point: Strings are heavily used in .NET applications for user registration, login systems, search functionality, form validation, API requests, database operations and reports.

Common String Mistakes

  • Remember that string indexing starts from 0.
  • Do not access an invalid string index.
  • Use Trim() when unwanted spaces may affect validation.
  • Use Contains() when checking whether specific text exists.
  • Remember that strings are immutable.
  • Use string interpolation for readable formatted text.

Interview Questions

1. What is a string in C#?

A string is a sequence of characters used to represent text.

2. Are strings mutable or immutable?

Strings are immutable in C#.

3. What is string interpolation?

String interpolation allows variables and expressions to be inserted directly into a string using the $ symbol.

4. What does the Length property return?

It returns the total number of characters in a string.

5. What is the difference between String and StringBuilder?

String is immutable, while StringBuilder is designed for efficient modification of strings when many changes are required.

Strings Summary

  • Strings are used to store text.
  • String indexing starts from 0.
  • The Length property returns the number of characters.
  • String concatenation joins multiple strings.
  • String interpolation provides readable formatted strings.
  • Common methods include Trim(), Contains(), Replace(), Split() and Substring().
  • Strings are immutable in C#.
  • Strings are widely used in real-world .NET applications.

Practice Questions

  1. Create a string variable and print its value.
  2. Find the length of a string.
  3. Convert a string to uppercase and lowercase.
  4. Remove unnecessary spaces using Trim().
  5. Check whether a string contains a specific word.
  6. Replace one word with another word.
  7. Extract a portion of a string using Substring().
  8. Split a comma-separated string into multiple values.
  9. Check whether an email ends with ".com".
  10. Reverse a string using a C# program.