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.
Creating a String
In C#, the string keyword is used to declare a string variable. String values are written inside double quotation marks.
using System;
string name = "Rahul";
Console.WriteLine(name);
Output
Rahul
String Declaration
A string can first be declared and then assigned a value.
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.
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.
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.
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
String Length
The Length property returns the total number of characters in a string.
using System;
string text = "Hello";
Console.WriteLine(text.Length);
Output
5
ToUpper()
The ToUpper() method converts all characters in a string to uppercase.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
- Create a string variable and print its value.
- Find the length of a string.
- Convert a string to uppercase and lowercase.
- Remove unnecessary spaces using Trim().
- Check whether a string contains a specific word.
- Replace one word with another word.
- Extract a portion of a string using Substring().
- Split a comma-separated string into multiple values.
- Check whether an email ends with ".com".
- Reverse a string using a C# program.