C# Strings & Methods
A string in C# is a sequence of characters used to represent text. Strings are enclosed in double quotes and have many built-in methods for manipulating text.
Strings in C# are immutable, meaning once created, a string's value cannot change. Methods like ToUpper(), Trim(), and Substring() return a new string rather than modifying the original.
string s = "Hello";
s.Length;
s.ToUpper();Common string methods
Length gives the number of characters, ToUpper()/ToLower() change case, Trim() removes whitespace from the ends, and Replace() swaps out text. Substring() extracts part of a string.
Combining strings
Strings can be joined with the + operator, or with string.Concat(). Since strings are immutable, each combination creates a new string object in memory.
using System;
class Program {
static void Main() {
string greeting = "Hello, World!";
Console.WriteLine(greeting.Length);
Console.WriteLine(greeting.ToUpper());
}
}13
HELLO, WORLD!Length returns the character count, and ToUpper() returns an uppercase copy.
using System;
class Program {
static void Main() {
string s = " Hello ";
Console.WriteLine(s.Trim());
Console.WriteLine(s.Trim().Replace("Hello", "Hi"));
}
}Hello
HiTrim() removes leading/trailing spaces, and Replace() substitutes text.
Key points
- Strings are sequences of characters enclosed in double quotes.
- Strings are immutable โ methods return new strings.
- Length gives the character count of a string.
- Common methods include ToUpper(), ToLower(), Trim(), and Replace().
