C# Tutorial menu

C# Strings

A string holds text. C# strings come with many built-in methods that make working with text easy.

Joining Strings

Example

csharp
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);
Output
Ayesha Siddiqui
Ayesha Siddiqui
AyeshaSiddiqui

String Properties and Methods

MemberWhat it gives
s.LengthNumber 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

csharp
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"));
Output
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

csharp
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]}");
Output
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

csharp
string saved = "Karachi";
string typed = "karachi";

Console.WriteLine(saved == typed);
Console.WriteLine(string.Equals(saved, typed, StringComparison.OrdinalIgnoreCase));
Output
False
True

Special Characters

CodeResult
\nNew line
\tTab
\"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

csharp
string path = @"C:\Users\Ali\Documents";
Console.WriteLine(path);
Output
C:\Users\Ali\Documents

Exercise

Exercise

What does "Pakistan".Substring(0, 3) return?

Learn C# with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp