C# Strings
A string holds text. C# strings come with many built-in methods that make working with text easy.
Joining Strings
Example
string first = "Ayesha";
string last = "Siddiqui";
string a = first + " " + last; // with +
string b = $"{first} {last}"; // with interpolation
string c = string.Concat(first, last);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);Ayesha Siddiqui Ayesha Siddiqui AyeshaSiddiqui
String Properties and Methods
| Member | What it gives |
|---|---|
s.Length | Number of characters (a property, no brackets) |
s.ToUpper() | Text in capitals |
s.ToLower() | Text in small letters |
s[i] | Character at index i |
s.IndexOf("x") | Position of the first match, or -1 |
s.Substring(start, length) | Part of the text |
s.Contains("x") | True if the text is found |
s.Replace("a", "b") | Text with replacements |
s.Trim() | Text without spaces at both ends |
s.Split(',') | An array of parts |
Example
string course = "Graphic Designing";
Console.WriteLine(course.Length);
Console.WriteLine(course.ToUpper());
Console.WriteLine(course[0]);
Console.WriteLine(course.IndexOf("Design"));
Console.WriteLine(course.Substring(8, 6));
Console.WriteLine(course.Contains("Web"));17 GRAPHIC DESIGNING G 8 Design False
Strings in C# are immutable: methods like ToUpper() or Replace() do not change the original string. They return a new one, so store the result: name = name.Trim();.
Splitting Text
Split breaks a string into an array. This is useful for data like a CSV line:
Example
string line = "Ali,Karachi,Web Development";
string[] parts = line.Split(',');
Console.WriteLine($"Name: {parts[0]}");
Console.WriteLine($"City: {parts[1]}");
Console.WriteLine($"Course: {parts[2]}");Name: Ali City: Karachi Course: Web Development
Comparing Strings
In C#, == compares the text of two strings. For a comparison that ignores capital letters, use string.Equals with an option:
Example
string saved = "Karachi";
string typed = "karachi";
Console.WriteLine(saved == typed);
Console.WriteLine(string.Equals(saved, typed, StringComparison.OrdinalIgnoreCase));False True
Special Characters
| Code | Result |
|---|---|
\n | New line |
\t | Tab |
\" | Double quote |
\\ | Backslash |
A string that starts with @ is a verbatim string: backslashes are kept as they are. It is handy for file paths:
Example
string path = @"C:\Users\Ali\Documents";
Console.WriteLine(path);C:\Users\Ali\Documents
Exercise
Exercise
What does "Pakistan".Substring(0, 3) return?
