TExcelTAD
Home › C# › C# Strings

C# Strings

A string stores text as a sequence of char values. Strings are used everywhere — names, messages, file contents — so the string type comes with a rich set of methods.

Creating strings and getting their length

csharp · try it yourself
using System;

string greeting = "Hello, C#";
string empty = "";

Console.WriteLine(greeting);
Console.WriteLine(greeting.Length);
Console.WriteLine(empty.Length);
Console.WriteLine(string.IsNullOrEmpty(empty));
Hello, C#
9
0
True

Length is a property (no parentheses), not a method.

Strings are immutable

Once created, a string never changes. Methods such as ToUpper or Replace return a new string and leave the original untouched — you must store the result if you want to keep it.

csharp · try it yourself
using System;

string word = "kitten";
word.ToUpper();                 // result is thrown away
Console.WriteLine(word);

string shout = word.ToUpper();  // keep the new string
Console.WriteLine(shout);
Console.WriteLine(word.Replace("k", "m"));
kitten
KITTEN
mitten

Useful string methods

Method Description Example → result
ToUpper() / ToLower() Change case "Hi".ToUpper() → "HI"
Trim() Remove surrounding whitespace " x ".Trim() → "x"
Contains(s) Does it contain s? "pizza".Contains("zz") → True
StartsWith(s) / EndsWith(s) Prefix / suffix test "file.cs".EndsWith(".cs") → True
IndexOf(s) Position of first match, or -1 "banana".IndexOf("n") → 2
Substring(start, len) Part of the string "banana".Substring(1, 3) → "ana"
Replace(a, b) Replace all occurrences "a-b-c".Replace("-", "") → "abc"
Split(c) Break into an array "a,b".Split(',') → ["a", "b"]
string.Join(sep, items) Glue items together string.Join("/", parts)
PadLeft(n) / PadRight(n) Pad to a width "7".PadLeft(3, '0') → "007"
csharp · try it yourself
using System;

string email = "  Ada.Lovelace@Example.com ";
string clean = email.Trim().ToLower();
Console.WriteLine(clean);

int at = clean.IndexOf('@');
string user = clean.Substring(0, at);
string domain = clean.Substring(at + 1);
Console.WriteLine(
quot;user={user}, domain={domain}"); string[] parts = user.Split('.'); Console.WriteLine(parts.Length); Console.WriteLine(string.Join(" ", parts).ToUpper()); Console.WriteLine("42".PadLeft(6, '0'));
ada.lovelace@example.com
user=ada.lovelace, domain=example.com
2
ADA LOVELACE
000042

Accessing characters

Use square brackets with a zero-based index to read a single char. The index-from-end operator ^1 gives the last character, and ranges (start..end) slice a string.

csharp · try it yourself
using System;

string lang = "CSharp";
Console.WriteLine(lang[0]);
Console.WriteLine(lang[^1]);
Console.WriteLine(lang[1..4]);
Console.WriteLine(lang[^3..]);

foreach (char c in "abc")
    Console.Write(c + "-");
Console.WriteLine();
C
p
Sha
arp
a-b-c-

Reading past the end (lang[10]) throws an IndexOutOfRangeException. And because strings are immutable, lang[0] = 'X' does not compile.

Comparing strings

== compares the text content (case-sensitive). For case-insensitive comparisons pass a StringComparison value:

csharp · try it yourself
using System;

string a = "Hello";
string b = "hello";

Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase));
Console.WriteLine(string.Compare("apple", "banana", StringComparison.Ordinal) < 0);
False
True
True

Building strings efficiently

Because every change creates a new string, gluing thousands of pieces together with + in a loop is slow. System.Text.StringBuilder keeps a growable buffer instead:

csharp · try it yourself
using System;
using System.Text;

var sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
    sb.Append(i);
    if (i < 5) sb.Append(" + ");
}
sb.Append(" = 15");
Console.WriteLine(sb.ToString());
1 + 2 + 3 + 4 + 5 = 15

Test yourself

What does "lighthouse".Substring(5, 3) return?

  1. "hou"
  2. "thou"
  3. "ous"
  4. "hous"

After string s = "abc"; s.ToUpper(); what is s?

  1. "ABC"
  2. "abc"
  3. null
  4. "Abc"

Which class should you use to build a long string in a loop?

  1. String
  2. StringBuilder
  3. Console
  4. Convert