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:
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:
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?
Treats \n as a newlineKeeps it as a literal backslashRemoves itCauses an error
Show answer
Answer: Keeps it as a literal backslash