Strings are one of the first data types you will use when learning C#. A name entered in a form, a message displayed on the screen, a product description, or an email address is all text. In C#, you usually store text in a string variable. A string is a sequence of UTF-16 code units that can represent letters, numbers, symbols, spaces, and many other characters. You write a normal string literal between double quotation marks, such as "Hello".
Learning strings in C# is important because most applications need to read, display, search, clean, or combine text. For example, an online store may join a customer's first and last names, a search feature may look for a word in a sentence, and a registration form may check whether someone entered an empty value. These tasks use different string methods, but they all start with understanding how text behaves.
A C# string belongs to the System.String class. The lowercase string keyword is an alias for System.String, so both refer to the same type. Although a string is a reference type, C# provides convenient syntax that makes it simple to work with. You can create a string, use its properties and methods, and print it with Console.WriteLine() without first learning every detail of object-oriented programming.
In this beginner-friendly lesson, you will learn how to create strings, join text with C# string concatenation, insert variables with string interpolation, work with common C# string methods, compare text correctly, and format output. You will also learn about string immutability, individual characters, special characters, slices, and StringBuilder. Each concept is explained before you need it, so you can understand why a method is useful instead of only memorizing its name.
Creating and combining strings
The simplest way to create a string in C# is to declare a variable with the string keyword and assign text between double quotes. This is called a string literal. You can also use String with a capital S, because string and System.String identify the same type. For most beginner programs, the lowercase keyword is the usual choice because it is short and familiar.
A string can contain ordinary letters, spaces, punctuation, and digits. Text such as "123" remains a string, not an integer, because the quotation marks tell C# to treat it as text. If you need to perform arithmetic, you must work with a numeric type or convert valid numeric text first. This distinction matters when values arrive from a form or from console input.
C# string concatenation means joining two or more pieces of text together. The + operator combines strings from left to right. It is useful for a short greeting or for adding a space between a first name and a last name. When you join a number to a string, C# can also format the value as text. However, long chains of + become harder to read, especially when you need spaces, punctuation, or several variables.
C# string interpolation provides a clearer way to insert values into a message. Place a $ before the opening quotation mark and put a variable or expression inside curly braces. C# evaluates the expression and places its result into the finished text. This can make greetings, receipts, status messages, and other output easier to maintain. Interpolation can also control number formatting, which you will see later.
string first = "Ada";
string last = "Lovelace";
string full = first + " " + last; // concatenation
string greeting = $"Hello, {first}!"; // interpolation
string sum = $"2 + 3 = {2 + 3}"; // expressions work too
The Length property tells you how many UTF-16 char values a string contains. For ordinary English words, that usually matches the number of visible letters. String indexing begins at zero: [0] accesses the first char, [1] the second, and [^1] the last. Be careful with empty strings, because accessing an index when no character exists causes an error.
A string literal is usually preferred over calling new string(...) when you already know the exact text. You can create a new string from a character array or repeated character if your program needs to construct text dynamically, but there is no reason to do that for a simple fixed greeting.
Common string methods
The C# string methods are built-in operations that help you process text without writing every step yourself. Some methods search for text, others produce a changed version of it, and others divide one string into smaller pieces. You call most of these methods using a dot after a string variable, such as name.Trim(). The dot lets you access members of the String type.
The most useful methods for beginners include ToUpper(), ToLower(), Trim(), Contains(), IndexOf(), Replace(), Substring(), Split(), and Join(). They solve everyday problems such as cleaning a name entered with extra spaces, locating a word in a sentence, or displaying data from several pieces. Understanding their return values will help you choose the right method.
| Method | Example | Result |
|---|
\|---|---|---|
\| ToUpper() / ToLower() | "Hi".ToUpper() | "HI" |
\| Trim() | " hi ".Trim() | "hi" |
\| Contains(x) | "hello".Contains("ell") | true |
\| StartsWith(x) / EndsWith(x) | "file.txt".EndsWith(".txt") | true |
\| IndexOf(x) | "banana".IndexOf("n") | 2 (or -1 if not found) |
\| Substring(start, length) | "Codevra".Substring(0, 4) | "Code" |
\| Replace(a, b) | "a-b-c".Replace("-", "+") | "a+b+c" |
\| Split(',') | "a,b,c".Split(',') | ["a", "b", "c"] |
\| string.Join(", ", items) | string.Join("-", parts) | "a-b-c" |
\| string.IsNullOrWhiteSpace(s) | string.IsNullOrWhiteSpace(" ") | true |
Changing letter case: ToUpper() produces uppercase text, while ToLower() produces lowercase text. These are useful for display or text cleanup, but converting case is not always the best approach for comparing values. When you need a case-insensitive comparison, a comparison option such as StringComparison.OrdinalIgnoreCase is normally more direct.
Removing unwanted whitespace: Trim() removes whitespace from the beginning and end of a string. TrimStart() only removes leading whitespace, and TrimEnd() only removes trailing whitespace. These methods do not remove spaces between words. They are useful when someone accidentally includes spaces before or after a name, but they are not a substitute for complete input validation.
Finding text: Contains() checks whether the requested sequence appears inside a string and returns true or false. StartsWith() and EndsWith() test the beginning and end. IndexOf() returns the starting index of the first matching occurrence, or -1 if it finds nothing. Use these methods when you want to check a prefix, locate a separator, or find a piece of text before extracting it.
Replacing and extracting: Replace() returns text with occurrences of one sequence exchanged for another. Substring() extracts part of a string using a start position and, optionally, a length. Because positions are zero-based, you should check a string's length before using indexes calculated from user input. A wrong position can cause an exception.
Splitting and joining: Split() separates text at selected delimiters and returns an array of strings. string.Join() does the reverse by combining several values using a chosen separator. For simple comma-separated text, Split(',') can be convenient. However, real CSV files can include quoted commas and other rules, so a dedicated CSV parser is better for full CSV support.
Most string methods do not change the original variable. They return a result that you can store or use in another expression. This behavior is central to C# string immutability and explains why calling Trim() alone does not permanently clean your variable.
Formatting, escapes and raw strings
C# string formatting controls how values appear when they are included in text. Formatting does not normally change the value stored in a numeric variable; it changes the way that value is displayed. This is useful for prices, percentages, large counts, reports, and neatly aligned console output.
With string interpolation, you can add a format specifier after a colon inside the braces. F2 displays a number with two digits after the decimal separator. N0 uses a number format with no decimal digits and usually includes group separators. P0 presents a number as a percentage without decimal digits. The exact decimal and grouping characters depend on the current culture, so output may look different across locales.
Alignment is another part of formatting. A value such as {name,-10} occupies a field at least ten characters wide and is left-aligned. A positive width right-aligns the value. Alignment is particularly helpful when printing receipt rows or small console tables because the numbers remain easier to scan.
Strings may also need characters that are awkward to type directly in source code. A C# escape sequence starts with a backslash. \n represents a new line, \t a tab, \" a quotation mark inside a regular string, and \\ a literal backslash. Escape sequences are useful for messages with multiple lines and text containing quotes, but a long sequence of escapes can make code difficult to read.
A verbatim string literal starts with @. In a verbatim string, a backslash is ordinarily treated as an actual backslash, making this form convenient for Windows paths and some regular expressions. To include a quotation mark inside a verbatim string, write two quotation marks. Verbatim strings can also extend across multiple lines.
Raw string literals, available in modern C#, begin and end with at least three quotation marks. They make it easier to write multiline JSON, SQL examples, or other structured text without escaping each quote or backslash. The indentation of a multiline raw literal affects the resulting value, so pay attention to the placement of the closing delimiter. Choose ordinary, verbatim, or raw literals according to which representation is most readable for the text you need.
Slicing with ranges and indexes
Sometimes you need only part of a string rather than the full text. You might want the first few letters of an identifier, the extension of a filename, or everything after a separator. In C#, you can use Substring() or C# string slicing with the range operator to extract that portion.
Substring(startIndex, length) uses a starting position and a number of char values to copy. If you omit the length, it returns the rest of the string. A range uses the form start..end, where the starting position is included and the ending position is excluded. The range form often makes it clearer where a slice starts and stops.
The ^ operator counts positions back from the end for index and range expressions. ^1 identifies the final char, while ^2 identifies the one before it. This is useful when the position you want is relative to the end rather than the start.
string word = "Codevra";
Console.WriteLine(word[..4]); // Code (first four characters)
Console.WriteLine(word[1..4]); // ode (indexes 1, 2 and 3)
Console.WriteLine(word[^3..]); // vra (last three characters)
Console.WriteLine(word[^1]); // a (last character, a char)
Both string ranges and Substring() require valid boundaries. If you use an index outside the text, the operation can throw an exception. When working with unpredictable input, check Length or find a separator first and confirm it exists. For instance, IndexOf() may return -1 when a delimiter is missing, and that value should not be passed blindly into a substring operation.
Remember that these operations deal with UTF-16 positions, not always whole visual characters. Many common letters use a single char, but some emoji and other Unicode characters use more than one. For beginner tasks involving plain English text, indexing usually behaves as expected. For advanced multilingual text editing, use Unicode-aware APIs rather than assuming every visible character occupies one index.
The extracted value is a new string, and the source remains unchanged. That makes ranges safe to use when you want to keep both the full text and a shorter portion of it.
Working with individual characters
A string contains char values, and C# lets you inspect them one at a time. This is useful when checking whether a password contains a digit, counting letters in a code, or looking for punctuation. A char is written between single quotes, whereas a string is written between double quotes. Although both represent text, a char holds one UTF-16 code unit and a string can hold many.
A foreach loop is a simple way to visit each char in order. The char type also provides helpful checks such as char.IsDigit(), char.IsLetter(), char.IsWhiteSpace(), and char.IsUpper(). These methods answer specific questions about a character, so they are generally easier to understand than manually checking ranges of character codes.
A string is a sequence of char values, so you can loop over it with foreach and test each character with the static methods on char:
int digits = 0;
foreach (char c in "Room 101")
{
if (char.IsDigit(c)) digits++;
}
Console.WriteLine(digits); // 3
Useful checks include char.IsLetter, char.IsDigit, char.IsWhiteSpace and char.IsUpper, and char.ToUpper('q') gives 'Q'. Each char is also a number underneath: (int)'A' is 65 and (char)66 is 'B'.
Because strings are immutable, you can't write word[0] = 'J'. When you need to change individual characters, copy them into an array, edit it and build a new string:
char[] letters = "hello".ToCharArray();
letters[0] = 'j';
string changed = new string(letters); // "jello"
new string('-', 10) is a related shortcut that repeats one character, which is handy for underlining headings in console output.
Understanding string immutability
A key rule of strings in C# is that a string object is immutable: after it has been created, its contents cannot be edited in place. This does not mean you can never change the value held by a string variable. It means that operations which appear to modify text create or return another string, and you can assign that result back to the variable.
For example, ToUpper() returns an uppercase result but leaves the original text untouched. The same principle applies to Replace(), Trim(), Substring(), and concatenation. A common beginner mistake is to call one of these methods and then assume the original variable now contains the updated text. Instead, save the returned value if you want to use it later.
String immutability makes it easier to reason about text because a method cannot silently alter the characters inside a string object that another part of your program is using. It can also involve creating temporary string objects when you repeatedly join or edit long text. In normal short expressions, that cost is usually not important. When you build a very large result one piece at a time, StringBuilder may be more appropriate.
C# strings are reference-type objects. The string keyword is simply an alias for System.String, and string literals may be interned so identical literals can reuse an existing object. Beginners generally do not need to manage string interning; it is more useful to focus on comparing text values instead of object identity.
Comparing strings in C#
C# string comparison is used whenever a program needs to decide whether two pieces of text match. The == operator compares the values of two strings. By default, this comparison is case-sensitive: uppercase and lowercase letters are not treated as interchangeable. This is useful for exact identifiers, but it may not match what a user expects when entering a name or command.
For case-insensitive checks, use string.Equals(first, second, StringComparison.OrdinalIgnoreCase) or a string method overload that accepts a StringComparison value. Ordinal comparison uses the underlying character values and is appropriate for many programmatic identifiers, tokens, and internal keys. OrdinalIgnoreCase ignores casing according to ordinal comparison rules without requiring you to generate uppercase copies.
You may also see StringComparison.CurrentCulture and related options. Culture-aware comparisons can be appropriate for text intended for people, such as sorting names in a user interface. There is no single comparison rule that is right for every situation. The important beginner habit is to choose whether the comparison should be case-sensitive and whether it should follow language-specific rules.
Searching methods can also accept comparison options. For example, when checking whether a phrase appears in user-visible text, decide whether capitalization should matter. Avoid converting both strings to lowercase just to compare them when a dedicated comparison API expresses the intent more clearly.
Checking for null, empty and whitespace strings
A string variable can contain text, an empty string, or potentially null. These are not the same state. The empty string "" exists but contains no char values; its Length is zero. A null reference means there is no string object to read at all. Accessing .Length on a null value raises a NullReferenceException.
string.IsNullOrEmpty(value) returns true when the input is null or empty. string.IsNullOrWhiteSpace(value) also treats a value consisting only of whitespace as blank. For many simple forms, the whitespace check is convenient because a user who enters spaces has not supplied meaningful text.
When you accept text from a user, first decide what counts as valid. A username might require at least a few visible characters. A comment field might allow spaces within the message but reject an input made entirely of spaces. The Trim() method can remove unwanted whitespace at the edges, but validation still needs to consider what your application expects.
In modern C#, nullable reference type annotations help communicate whether a string is expected to contain null. A declaration such as string? nickname explicitly allows null when nullable reference types are enabled. These annotations help the compiler warn about risky access, but they do not replace checking external data at runtime.
Splitting, joining and replacing text
A frequent task in C# string manipulation is turning one piece of text into several parts. Split() divides a string using a delimiter such as a comma, space, or semicolon. It returns an array, so you can examine each piece separately. This is useful for a basic list of tags, an uncomplicated settings line, or a command containing several words.
By default, splitting can keep empty entries. If the input contains consecutive delimiters, one of the returned elements may be an empty string. StringSplitOptions.RemoveEmptyEntries tells C# to skip those entries. StringSplitOptions.TrimEntries removes surrounding whitespace from the produced parts. When these options are supported by your target framework, they help clean simple structured input.
To combine parts again, use string.Join(separator, values). It inserts a chosen separator between the array elements and returns one completed string. Unlike repeatedly adding punctuation by hand, Join() makes it easier to avoid unnecessary separators before the first item or after the last one.
Replace() is useful when the rule is simply to exchange one character or sequence for another. It does not understand grammar or the meaning of words, so a broad replacement may change more text than you intended. If you need to replace a whole word rather than every matching sequence, consider a more specific approach.
These methods are excellent for simple teaching examples, but they have limits. In particular, parsing genuine CSV files is more complicated than calling Split(','), because a field can contain commas inside quoted text. Use a proper parser when handling actual CSV uploads.
Using StringBuilder for longer text
For a short message, string concatenation and interpolation are clear and convenient. But when a program repeatedly appends thousands of pieces inside a loop, creating a fresh string on every step can require unnecessary copying. The C# StringBuilder class is designed for efficiently constructing text through repeated changes.
StringBuilder is available in the System.Text namespace. You create a builder, add content using Append() or AppendLine(), and call ToString() when you need a regular string. AppendLine() adds a line ending, making it useful for reports, generated messages, and plain-text documents.
The difference between string and StringBuilder in C# is mainly how they handle change. A string is immutable, while a StringBuilder holds a changeable sequence of characters. That allows a builder to add or replace pieces without creating an entirely new string for every append. It does not mean StringBuilder is always faster in every situation, and it is unnecessary for a few simple words.
Choose interpolation when a message has several fixed parts and a few variables. Choose string.Join() when combining a collection with a separator. Consider StringBuilder when the number of pieces is large, the final text grows in a loop, or you are generating a lengthy report. Matching the tool to the task keeps the code readable without adding complexity too early.
Common string mistakes and practical tips
When learning how to use strings in C#, a few mistakes appear regularly. The first is confusing char and string. Single quotes create a character literal, while double quotes create a string literal. You cannot treat the two as interchangeable in every method call. Use the form that matches the type the method expects.
Another mistake is assuming indexing begins at one. In C#, the first char is at position zero, and attempting to read a position outside the string causes an exception. Validate positions before extracting parts of unpredictable text. Similarly, always remember that IndexOf() returns -1 when there is no match.
Be careful with case-sensitive comparisons. A check that works for "Admin" may not match "admin". Rather than trying random conversions until the program works, choose a comparison rule that matches the meaning of your data. For simple internal identifiers, ordinal comparisons are usually a sensible default.
Also remember that some formatting depends on culture. A number may use different decimal separators or grouping characters on different machines. When formatting text for people, using the intended culture helps. When producing data for another program, an explicit invariant format may be more appropriate.
Finally, treat string operations as useful building blocks rather than complete validation or security features. Trimming a field does not prove that it is a valid email address, and checking a filename extension does not prove that an uploaded file is safe. Use the appropriate validation and parsing tools for real applications, while using string methods for the straightforward text operations they are designed to perform.
C# Strings Syntax
String operations
string s = " Hello World ";
s.Trim().ToLower() // "hello world"
s.Contains("World") // true
s.Trim().Split(' ') // ["Hello", "World"]
string.Join(", ", new[] { "a", "b" }) // "a, b"
$"{price:F2}" $"{big:N0}" $"{share:P1}"
"line1\nline2" @"C:\temp" """He said "hi" """
var sb = new System.Text.StringBuilder();
sb.Append("a").AppendLine("b");
string result = sb.ToString();
C# Strings Summary
- Strings are text in double quotes; $"...{x}..." interpolates values and expressions.
- Length, indexing from 0 and ^1 for the last character.
- ToUpper, Trim, Contains, IndexOf, Substring, Replace, Split and Join cover most tasks.
- Format specifiers such as :F2 and :N0 control how numbers appear.
- Strings are immutable; use StringBuilder to build long text in steps.
C# Strings Examples
Each example shows the code, the output it produces and what each part does.
Cleaning up a name
string input = " ada LOVELACE ";
string trimmed = input.Trim();
string[] parts = trimmed.Split(' ');
string first = parts[0][0].ToString().ToUpper() + parts[0].Substring(1).ToLower();
string last = parts[1][0].ToString().ToUpper() + parts[1].Substring(1).ToLower();
Console.WriteLine($"[{trimmed}]");
Console.WriteLine($"{first} {last}");
Console.WriteLine($"Initials: {first[0]}{last[0]}");
Console.WriteLine($"Length: {first.Length + last.Length}");
[ada LOVELACE]
Ada Lovelace
Initials: AL
Length: 11
Line-by-line explanation
- Line 2Trim removes spaces from both ends.
- Line 3Split breaks the text at each space into an array.
- Line 5The first letter is uppercased and the rest of the word lowercased.
- Line 10Indexing a string gives a char.
- Line 11Ada has 3 letters and Lovelace has 8.
Formatting a receipt
string[] items = { "Coffee", "Croissant", "Orange juice" };
decimal[] prices = { 2.8m, 2.25m, 3.5m };
decimal total = 0;
for (int i = 0; i < items.Length; i++)
{
Console.WriteLine($"{items[i],-14}{prices[i],6:F2}");
total += prices[i];
}
Console.WriteLine(new string('-', 20));
Console.WriteLine($"{"Total",-14}{total,6:F2}");
Console.WriteLine($"Visitors: {1234567:N0}");
Coffee 2.80
Croissant 2.25
Orange juice 3.50
--------------------
Total 8.55
Visitors: 1,234,567
Line-by-line explanation
- Line 7,-14 pads the name to 14 characters on the left; ,6:F2 right-aligns the price in 6 characters with two decimals.
- Line 10new string('-', 20) repeats a character 20 times.
- Line 12N0 adds thousands separators (shown here with English formatting).
Searching, replacing and StringBuilder
using System.Text;
string email = "Ada.Lovelace\@Example.com";
int at = email.IndexOf('@');
string user = email.Substring(0, at);
string domain = email[(at + 1)..].ToLower();
Console.WriteLine(user);
Console.WriteLine(domain);
Console.WriteLine(email.EndsWith(".com"));
Console.WriteLine(string.Equals(email, "ada.lovelace\@example.com", StringComparison.OrdinalIgnoreCase));
Console.WriteLine("2026-03-01".Replace("-", "/"));
var sb = new StringBuilder();
for (int i = 1; i <= 3; i++)
{
sb.Append($"Row {i}; ");
}
Console.WriteLine(sb.ToString().TrimEnd());
Ada.Lovelace
example.com
True
True
2026/03/01
Row 1; Row 2; Row 3;
Line-by-line explanation
- Line 4IndexOf finds the position of the @ sign.
- Line 5Substring(0, at) takes everything before it.
- Line 6[(at + 1)..] is a range: everything after the @.
- Line 11OrdinalIgnoreCase compares without caring about capital letters.
- Lines 14 to 18StringBuilder adds pieces to one buffer instead of creating a new string each time.
- Line 19TrimEnd removes the trailing space.
Common C# Strings Mistakes
Expecting a method to change the string
string name = "ada";
name.ToUpper();
Console.WriteLine(name); // still "ada"
string name = "ada";
name = name.ToUpper();
Building a big string with += in a loop
string report = "";
foreach (var line in lines) report += line + "\n"; // slow for thousands of lines
var sb = new StringBuilder();
foreach (var line in lines) sb.AppendLine(line);
string report = sb.ToString();
Backslashes in a normal string
string path = "C:\new\test.txt"; // \n and \t become a new line and a tab
string path = @"C:\new\test.txt";
C# Strings in Real Projects
Strings in applications
Web APIs trim and validate form fields, compare emails ignoring case, and build messages with interpolation. Simple delimited input can be split with Split(','), while real CSV imports need a CSV parser. Logging libraries use interpolation-style templates, and report generators use StringBuilder to assemble large documents. Raw string literals keep JSON and SQL samples readable in tests.
C# Strings FAQ
How do I check if a string is empty or null in C#?
Use string.IsNullOrEmpty(s) to catch both null and "", or string.IsNullOrWhiteSpace(s) to also treat strings made only of spaces as empty. The second is usually the better choice for user input. Checking s.Length == 0 on its own throws a NullReferenceException when s is null.
What is the difference between string interpolation and string.Format?
Both produce the same text. Interpolation, $"Total: {total:F2}", puts the values directly inside the braces, while string.Format("Total: {0:F2}", total) uses numbered placeholders and a separate argument list. Interpolation is easier to read and is the usual choice in modern C#.
How do I split a string and ignore empty entries?
Pass StringSplitOptions.RemoveEmptyEntries: "a,b,,c".Split(',', StringSplitOptions.RemoveEmptyEntries) gives three items instead of four. Add StringSplitOptions.TrimEntries as well, combined with |, to remove spaces around each piece.
Why can't I change a character in a C# string?
Strings are immutable, so the indexer s[0] is read-only and s[0] = 'X' doesn't compile. Build a new string instead, for example with Replace, with ranges and concatenation, or by editing a char[] from ToCharArray() and passing it to new string(...). For lots of changes, use StringBuilder.
When should I use StringBuilder instead of +?
Use StringBuilder when you build a string in a loop or from many pieces, because each + creates a brand-new string and copies everything so far. For joining a few values on one line, + or interpolation is perfectly fine and easier to read.
C# Strings Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so the message includes the name.
string name = "Sam";
Console.WriteLine("Hi {name}");
What does this print?
Console.WriteLine("banana".IndexOf("n"));
What does this print?
string s = "a,b,,c";
Console.WriteLine(s.Split(',').Length);
What does $"{9.5:F2}" produce?
Why is StringBuilder faster than += when building a long string in a loop?
C# Strings Quiz
5 questions to check what you learned.
What does
"Hello".Lengthreturn?- 4
- 5
- 6
- "Hello"
How do you compare two strings ignoring case?
- a == b
- string.Equals(a, b, StringComparison.OrdinalIgnoreCase)
- a.Compare(b)
- a.ToUpper() = b
What does @ before a string literal do?
- Interpolates values
- Makes it a char
- Makes it constant
- Makes a verbatim string where backslashes are literal
What does
"Codevra".Substring(4)return?- "Code"
- "evra"
- "vra"
- "v"
What does
"abc"[^1]give?- 'c'
- 'a'
- 'b'
- An error