C# — Strings
String basics
using System;
string s1 = "Hello";
string s2 = "World";
string s3 = string.Concat(s1, " ", s2);
string s4 = $"{s1} {s2}"; // Interpolation
Console.WriteLine(s4); // Hello World
Console.WriteLine(s4.Length); // 11
String operations
using System;
string s = "Hello, World!";
Console.WriteLine(s.Substring(0, 5)); // Hello
Console.WriteLine(s.IndexOf("World")); // 7
Console.WriteLine(s.Contains("World")); // True
Console.WriteLine(s.Replace("World", "C#")); // Hello, C#!
Console.WriteLine(s.ToUpper()); // HELLO, WORLD!
Console.WriteLine(s.ToLower()); // hello, world!
Console.WriteLine(s.Trim()); // Hello, World!
Console.WriteLine(s.StartsWith("Hello")); // True
Console.WriteLine(s.EndsWith("!")); // True
Console.WriteLine(s[0]); // H
String comparison
using System;
string a = "Hello";
string b = "hello";
Console.WriteLine(a == b); // False (case-sensitive)
Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine(string.Compare(a, b, StringComparison.OrdinalIgnoreCase)); // 0
// Reference vs value equality
string s1 = "Hello";
string s2 = "Hello";
Console.WriteLine(s1 == s2); // True (value equality)
Console.WriteLine(ReferenceEquals(s1, s2)); // May be True (interning)
String methods
using System;
// Split
string csv = "apple,banana,cherry";
string[] fruits = csv.Split(',');
foreach (var f in fruits)
Console.WriteLine(f);
// Join
string joined = string.Join(" | ", fruits);
Console.WriteLine(joined); // apple | banana | cherry
// Pad
Console.WriteLine("42".PadLeft(5, '0')); // 00042
Console.WriteLine("Hi".PadRight(10, '-')); // Hi--------
// Contains and starts/ends
Console.WriteLine("Hello".Contains("ell")); // True
Console.WriteLine("Hello".StartsWith("He")); // True
Console.WriteLine("Hello".EndsWith("lo")); // True
StringBuilder
For efficient string manipulation:
using System;
using System.Text;
var sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
sb.Insert(5, ",");
sb.Replace("World", "C#");
string result = sb.ToString();
Console.WriteLine(result); // Hello, C#
// StringBuilder with capacity
var sb2 = new StringBuilder(100); // Pre-allocate
for (int i = 0; i < 50; i++)
{
sb2.Append(i).Append(" ");
}
Console.WriteLine(sb2.ToString());
String interpolation
using System;
string name = "Alice";
int age = 30;
double score = 95.5;
// Basic interpolation
Console.WriteLine($"{name} is {age} years old");
// Expressions
Console.WriteLine($"Next year: {age + 1}");
Console.WriteLine($"Uppercase: {name.ToUpper()}");
// Format specifiers
Console.WriteLine($"Score: {score:F2}"); // 95.50
Console.WriteLine($"Score: {score:P0}"); // 9550%
// Alignment
Console.WriteLine($"{"Name",-10} {"Score",5}");
Console.WriteLine($"{"Alice",-10} {score,5:F1}");
Raw string literals (C# 11)
using System;
// No escape needed
string path = """C:\Users\Alice\Documents""";
Console.WriteLine(path);
// Multi-line
string json = """
{
"name": "Alice",
"age": 30
}
""";
Console.WriteLine(json);
String and char arrays
using System;
string s = "Hello";
// To char array
char[] chars = s.ToCharArray();
Array.Reverse(chars);
Console.WriteLine(new string(chars)); // olleH
// From char array
string fromChars = new string(new[] { 'H', 'i' });
Console.WriteLine(fromChars); // Hi
// Char operations
Console.WriteLine(char.IsLetter('A')); // True
Console.WriteLine(char.IsDigit('5')); // True
Console.WriteLine(char.ToUpper('a')); // A
Common patterns
using System;
// Null/empty checks
string? s = null;
Console.WriteLine(string.IsNullOrEmpty(s)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(s)); // True
// String interpolation for file paths
string name = "report";
string path = $@"C:\Users\Documents\{name}.txt";
Console.WriteLine(path);
// String interpolation for SQL (use parameters in real code!)
string table = "users";
string query = $"SELECT * FROM {table} WHERE active = 1";
Console.WriteLine(query);
Mini Practice
Write C# code that:
- Splits a CSV string and prints each field
- Uses
StringBuilderto build a large string efficiently - Demonstrates string interpolation with alignment
- Converts a string to a char array and reverses it
Up Next
In the next lesson, you'll learn about If Else — conditional branching in C#.
Related Topics
Frequently Asked Questions about Strings
What is Strings in C#?
Strings is a fundamental concept in C#. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Strings?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.
Why is Strings important in C#?
Strings is essential for C# development. Understanding this concept will help you write better code and solve real-world problems more effectively.