C# Tutorial · C# Basics · Lesson 5 of 22

C# Strings

String methods, comparison, verbatim and raw strings, and StringBuilder.

Working with strings

Strings are immutable; methods return new strings:

Example 1
string s = "  Hello, C#  ";
string t = s.Trim();
Console.WriteLine(t.Length);
Console.WriteLine(t.ToUpper());
Console.WriteLine(t.Contains("C#") + " " + t.StartsWith("Hello") + " " + t.IndexOf(","));
Console.WriteLine(t.Substring(7) + " | " + t[..5]);
Console.WriteLine(t.Replace("C#", "World"));
Console.WriteLine(string.Join("-", "a,b,c".Split(',')));
Console.WriteLine(string.Equals("abc", "ABC", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(string.IsNullOrWhiteSpace("   "));
Console.WriteLine(@"C:\temp\new");

Output

9
HELLO, C#
True True 5
C# | Hello
Hello, World
a-b-c
True
True
C:\temp\new

Run this on your computer — see “Get Started” for setup.

Special string literals

  • @"C:\path" — verbatim string: backslashes aren't escapes.
  • Raw string literals (C# 11) — text between three double quotes — for multi-line text and JSON.

StringBuilder

Use System.Text.StringBuilder to build strings in loops:

Example 2
using System.Text;

var sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
    sb.Append(i);
    if (i < 5) sb.Append(", ");
}
Console.WriteLine(sb.ToString());
string json = """
    {
      "name": "Ada"
    }
    """;
Console.WriteLine(json);

Output

1, 2, 3, 4, 5
{
  "name": "Ada"
}

Run this on your computer — see “Get Started” for setup.

Test yourself

What does a verbatim string @"C:\new" do with the backslash?

  1. Treats \n as a newline
  2. Keeps it as a literal backslash
  3. Removes it
  4. Causes an error
Show answer

Answer: Keeps it as a literal backslash