C# String Functions

Strings are immutable text sequences: every method returns a new string. Learn the literals, the common String API, and StringBuilder for heavy work.

String Basics

Literals

Literals are values written directly into the code. Double quotes mark a string, single quotes mark one character, and numbers and booleans need no quotes.

string greeting = "Hello";
char letter = 'A';
string empty = "";

Verbatim Strings

A verbatim string (@) skips escape processing — handy for paths and multi-line text.

string path = @"C:\data\file.txt";
string multi = @"line one
line two";

Interpolation

Embed expressions directly with $"...".

string name = "Ada";
Console.WriteLine($"Hi {name}");   // Hi Ada
Console.WriteLine($"2+2 = {2 + 2}"); // 2+2 = 4

Common Methods

Compare & Equals

Prefer Equals with an explicit comparison rule so the intent is visible. The default == also compares strings by value in C#.

string a = "hello";
string b = "HELLO";
Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine(string.Compare(a, "hello")); // 0 — equal

Testing membership and position helps you validate user input and parse text. Each method below answers a different question.

string text = "hello world";
Console.WriteLine(text.Contains("world")); // True  — does text contain it?
Console.WriteLine(text.StartsWith("he"));  // True  — how does it begin?
Console.WriteLine(text.IndexOf("world"));  // 6     — where does it start?

Modify

Strings are immutable, so each call returns a new string.

string t = "  Hello  ";
Console.WriteLine(t.Trim().ToUpper());            // HELLO
Console.WriteLine("a,b".Replace(",", ";"));       // a;b
Console.WriteLine("program".Substring(3));        // gram

Split & Join

Split and Join

Splitting breaks a string into an array on a separator; joining does the reverse. This round-trip is the basis of CSV parsing.

string data = "a,b,c";
string[] parts = data.Split(',');
string joined = string.Join(" | ", parts); // a | b | c

StringBuilder

For repeated concatenation in a loop, use StringBuilder — it avoids creating a new string each time.

using System.Text;

var sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
    sb.Append(i).Append(' ');
}
string result = sb.ToString();