×

C# Crash Course

Course Home C# Introduction and Setup C# Variables and Data Types C# Console Input and Output C# Operators and Expressions C# Conditional Statements - If and Else C# Switch Statements C# While and Do-While Loops C# For Loops C# Nested Loops C# Methods - Part 1 (Basics) C# Methods - Part 2 (ref, out, and Recursion) C# Arrays C# Number Systems (Binary and Hexadecimal) C# Exception Handling (Try-Catch) C# Random Numbers C# String Methods and Manipulation C# Course Summary and Best Practices


C# String Methods and Manipulation

What is a String?

A string is a sequence of characters used to represent text. Strings are one of the most commonly used data types in programming.

string sName = "John";
string sMessage = "Hello World!";
string sEmpty = "";

String Properties

Length Property

Returns the number of characters in a string.

string sName = "Alice";
int iLength = sName.Length;
Console.WriteLine(iLength);  // 5

string sMessage = "Hello World!";
Console.WriteLine(sMessage.Length);  // 12

Accessing Characters by Index

Strings use zero-based indexing like arrays.

string sName = "Hello";
char cFirst = sName[0];   // 'H'
char cSecond = sName[1];  // 'e'
char cLast = sName[4];    // 'o'

Console.WriteLine(cFirst);   // H
Console.WriteLine(cLast);    // o

String Methods

ToUpper() and ToLower()

Convert string to uppercase or lowercase.

string sName = "Alice";

string sUpper = sName.ToUpper();  // "ALICE"
string sLower = sName.ToLower();  // "alice"

Console.WriteLine(sUpper);  // ALICE
Console.WriteLine(sLower);  // alice

Practical Use:

Console.Write("Are you employed? (Y/N): ");
string sInput = Console.ReadLine().ToUpper();

if (sInput == "Y")
{
    Console.WriteLine("You are employed");
}

Trim(), TrimStart(), TrimEnd()

Remove whitespace from strings.

string sText = "   Hello World   ";

string sTrimmed = sText.Trim();           // "Hello World"
string sTrimStart = sText.TrimStart();    // "Hello World   "
string sTrimEnd = sText.TrimEnd();        // "   Hello World"

Console.WriteLine($"'{sTrimmed}'");      // 'Hello World'

Substring()

Extract a portion of a string.

string sText = "Hello World";

// Substring(startIndex)
string sPart1 = sText.Substring(6);      // "World"

// Substring(startIndex, length)
string sPart2 = sText.Substring(0, 5);   // "Hello"
string sPart3 = sText.Substring(6, 3);   // "Wor"

Console.WriteLine(sPart1);  // World
Console.WriteLine(sPart2);  // Hello

Contains()

Check if a string contains a substring.

string sEmail = "john@example.com";

bool bHasAt = sEmail.Contains("@");       // true
bool bHasCom = sEmail.Contains(".com");   // true
bool bHasXyz = sEmail.Contains("xyz");    // false

Console.WriteLine(bHasAt);   // True
Console.WriteLine(bHasXyz);  // False

StartsWith() and EndsWith()

Check if string starts or ends with specific text.

string sFileName = "document.pdf";

bool bStartsWithDoc = sFileName.StartsWith("doc");   // true
bool bEndsWithPdf = sFileName.EndsWith(".pdf");      // true
bool bEndsWithTxt = sFileName.EndsWith(".txt");      // false

Console.WriteLine(bEndsWithPdf);  // True

IndexOf() and LastIndexOf()

Find the position of a character or substring.

string sText = "Hello World";

int iPos1 = sText.IndexOf('o');        // 4 (first 'o')
int iPos2 = sText.LastIndexOf('o');    // 7 (last 'o')
int iPos3 = sText.IndexOf("World");    // 6
int iPos4 = sText.IndexOf('z');        // -1 (not found)

Console.WriteLine(iPos1);  // 4
Console.WriteLine(iPos2);  // 7
Console.WriteLine(iPos4);  // -1

Replace()

Replace characters or substrings.

string sText = "Hello World";

string sReplaced1 = sText.Replace('o', 'a');           // "Hella Warld"
string sReplaced2 = sText.Replace("World", "C#");      // "Hello C#"
string sReplaced3 = sText.Replace(" ", "");            // "HelloWorld"

Console.WriteLine(sReplaced1);  // Hella Warld
Console.WriteLine(sReplaced2);  // Hello C#

Split()

Split a string into an array of strings.

string sData = "John,25,Engineer";
string[] sParts = sData.Split(',');

Console.WriteLine(sParts[0]);  // John
Console.WriteLine(sParts[1]);  // 25
Console.WriteLine(sParts[2]);  // Engineer

// Split by space
string sSentence = "Hello World Programming";
string[] sWords = sSentence.Split(' ');

foreach (string sWord in sWords)
{
    Console.WriteLine(sWord);
}
// Output:
// Hello
// World
// Programming

Insert()

Insert text at a specific position.

string sText = "Hello World";
string sInserted = sText.Insert(6, "Beautiful ");

Console.WriteLine(sInserted);  // Hello Beautiful World

Remove()

Remove characters from a string.

string sText = "Hello World";

string sRemoved1 = sText.Remove(5);        // "Hello" (removes from index 5 to end)
string sRemoved2 = sText.Remove(5, 6);     // "Hello" (removes 6 chars from index 5)

Console.WriteLine(sRemoved1);  // Hello
Console.WriteLine(sRemoved2);  // Hello

String Concatenation

Using + Operator

string sFirst = "Hello";
string sLast = "World";
string sFull = sFirst + " " + sLast;

Console.WriteLine(sFull);  // Hello World

Using String.Concat()

string sResult = String.Concat("Hello", " ", "World");
Console.WriteLine(sResult);  // Hello World

Using String Interpolation (Recommended)

string sName = "Alice";
int iAge = 25;
string sMessage = $"My name is {sName} and I am {iAge} years old";

Console.WriteLine(sMessage);
// Output: My name is Alice and I am 25 years old

Using StringBuilder (For Multiple Concatenations)

using System.Text;

StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");

string sResult = sb.ToString();
Console.WriteLine(sResult);  // Hello World

String Comparison

Using == Operator

string sName1 = "Alice";
string sName2 = "Alice";
string sName3 = "Bob";

bool bEqual1 = (sName1 == sName2);  // true
bool bEqual2 = (sName1 == sName3);  // false

Console.WriteLine(bEqual1);  // True
Console.WriteLine(bEqual2);  // False

Case-Insensitive Comparison

string sStr1 = "Hello";
string sStr2 = "hello";

// Case-sensitive (different)
bool bEqual1 = (sStr1 == sStr2);  // false

// Case-insensitive (same)
bool bEqual2 = sStr1.ToLower() == sStr2.ToLower();  // true
bool bEqual3 = String.Equals(sStr1, sStr2, StringComparison.OrdinalIgnoreCase);  // true

Console.WriteLine(bEqual1);  // False
Console.WriteLine(bEqual2);  // True

CompareTo()

Compare strings alphabetically.

string sStr1 = "Apple";
string sStr2 = "Banana";

int iResult = sStr1.CompareTo(sStr2);
// Returns: negative if str1 < str2
//          0 if str1 == str2
//          positive if str1 > str2

Console.WriteLine(iResult);  // Negative number (Apple comes before Banana)

Checking Empty or Null Strings

IsNullOrEmpty()

string sEmpty = "";
string sNull = null;
string sValid = "Hello";

bool bCheck1 = String.IsNullOrEmpty(sEmpty);  // true
bool bCheck2 = String.IsNullOrEmpty(sNull);   // true
bool bCheck3 = String.IsNullOrEmpty(sValid);  // false

Console.WriteLine(bCheck1);  // True
Console.WriteLine(bCheck3);  // False

IsNullOrWhiteSpace()

string sSpaces = "   ";
string sEmpty = "";
string sValid = "Hello";

bool bCheck1 = String.IsNullOrWhiteSpace(sSpaces);  // true
bool bCheck2 = String.IsNullOrWhiteSpace(sEmpty);   // true
bool bCheck3 = String.IsNullOrWhiteSpace(sValid);   // false

Console.WriteLine(bCheck1);  // True
Console.WriteLine(bCheck3);  // False

Practical Examples

Example 1: Email Validator

using System;

namespace EmailValidator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter email address: ");
            string sEmail = Console.ReadLine();

            if (IsValidEmail(sEmail))
            {
                Console.WriteLine("Valid email address");
            }
            else
            {
                Console.WriteLine("Invalid email address");
            }

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }

        static bool IsValidEmail(string sEmail)
        {
            if (String.IsNullOrWhiteSpace(sEmail))
            {
                return false;
            }

            if (!sEmail.Contains("@"))
            {
                return false;
            }

            if (!sEmail.Contains("."))
            {
                return false;
            }

            int iAtPos = sEmail.IndexOf('@');
            int iDotPos = sEmail.LastIndexOf('.');

            if (iAtPos > iDotPos)
            {
                return false;
            }

            return true;
        }
    }
}

Example 2: Word Counter

using System;

namespace WordCounter
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a sentence: ");
            string sSentence = Console.ReadLine();

            int iWordCount = CountWords(sSentence);

            Console.WriteLine($"\nNumber of words: {iWordCount}");

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }

        static int CountWords(string sText)
        {
            if (String.IsNullOrWhiteSpace(sText))
            {
                return 0;
            }

            string sTrimmed = sText.Trim();
            string[] sWords = sTrimmed.Split(' ');

            return sWords.Length;
        }
    }
}

Example 3: String Reverser

using System;

namespace StringReverser
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a string: ");
            string sInput = Console.ReadLine();

            string sReversed = ReverseString(sInput);

            Console.WriteLine($"\nReversed: {sReversed}");

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }

        static string ReverseString(string sText)
        {
            string sResult = "";

            for (int i = sText.Length - 1; i >= 0; i--)
            {
                sResult += sText[i];
            }

            return sResult;
        }
    }
}

Example 4: Palindrome Checker

using System;

namespace PalindromeChecker
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a word: ");
            string sWord = Console.ReadLine().ToLower();

            if (IsPalindrome(sWord))
            {
                Console.WriteLine($"\n'{sWord}' is a palindrome");
            }
            else
            {
                Console.WriteLine($"\n'{sWord}' is not a palindrome");
            }

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }

        static bool IsPalindrome(string sText)
        {
            string sReversed = "";

            for (int i = sText.Length - 1; i >= 0; i--)
            {
                sReversed += sText[i];
            }

            return sText == sReversed;
        }
    }
}

Example 5: Name Formatter

using System;

namespace NameFormatter
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter your full name: ");
            string sFullName = Console.ReadLine();

            string sFormatted = FormatName(sFullName);

            Console.WriteLine($"\nFormatted name: {sFormatted}");

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }

        static string FormatName(string sName)
        {
            string sTrimmed = sName.Trim();
            string[] sParts = sTrimmed.Split(' ');
            string sResult = "";

            foreach (string sPart in sParts)
            {
                if (sPart.Length > 0)
                {
                    // Capitalize first letter, lowercase rest
                    string sFormatted = sPart.Substring(0, 1).ToUpper() + 
                                       sPart.Substring(1).ToLower();
                    sResult += sFormatted + " ";
                }
            }

            return sResult.Trim();
        }
    }
}

String Escape Sequences (Recap)

Sequence Description Example
\n New line "Line1\nLine2"
\t Tab "Name\tAge"
\\ Backslash "C:\\Files"
\" Double quote "He said \"Hi\""
\' Single quote 'It\'s'

Practice Exercises

Exercise 1: Count Vowels

Write a program that counts the number of vowels (a, e, i, o, u) in a string.

Exercise 2: Remove Spaces

Write a program that removes all spaces from a string.

Exercise 3: Find Longest Word

Write a program that finds the longest word in a sentence.

Exercise 4: Acronym Generator

Write a program that creates an acronym from a phrase. Example: "Central Processing Unit" → "CPU"

Exercise 5: Password Strength Checker

Check if password has: - At least 8 characters - Contains uppercase and lowercase - Contains a number

Common Mistakes to Avoid

Modifying string directly (strings are immutable):

string sText = "Hello";
sText[0] = 'J';  // ERROR! Cannot modify

Correct - Create new string:

string sText = "Hello";
sText = "J" + sText.Substring(1);  // "Jello"

Forgetting string indices are zero-based:

string sText = "Hello";
char cLast = sText[5];  // ERROR! Index out of range

Correct:

char cLast = sText[4];  // 'o'
// Or
char cLast = sText[sText.Length - 1];

Not handling null strings:

string sName = null;
int iLength = sName.Length;  // CRASH!

Correct:

if (sName != null)
{
    int iLength = sName.Length;
}
// Or
if (!String.IsNullOrEmpty(sName))
{
    int iLength = sName.Length;
}

Key Takeaways

✅ Strings are immutable (cannot be modified) ✅ Use .Length to get string length ✅ Strings use zero-based indexing ✅ .ToUpper() and .ToLower() for case conversion ✅ .Trim() removes whitespace ✅ .Substring() extracts part of string ✅ .Contains() checks if substring exists ✅ .Replace() replaces text ✅ .Split() divides string into array ✅ Use string interpolation $"" for formatting ✅ Use IsNullOrEmpty() or IsNullOrWhiteSpace() to check for empty strings


Next Topic: C# Course Summary and Best Practices