CodeBlanks Logo Icon CodeBlanks

String helpers

C# course · Intermediate · Lesson 20/116

Add and test string processing methods.

String helpers

Our first helper method is Capitalize: it uppercases only the first letter of a string. Declaration: public static string Capitalize(string text). Being static, it is called directly as Helpers.Capitalize("hello").

In the body we first check for empty with string.IsNullOrEmpty(text); then we uppercase the first letter with char.ToUpper(text[0]) and append the rest with text.Substring(1). Result: "Hello". This is useful to clean up names entered by users.

Using Capitalize

Once you write a helper method, you can call it from anywhere. Example: string name = Helpers.Capitalize("alex");. This puts user input into a consistent form.

This is why helper libraries are valuable: write once, use a thousand times. Instead of copying the same code, you call Helpers.Capitalize. If you find a bug, you fix it in one place; all callers update automatically.

Exercise Add the Capitalize method and call it

The Helpers class below is empty. Add a public static string Capitalize(string text) method to it. In the body check for empty with if (string.IsNullOrEmpty(text)) return text;, then write return char.ToUpper(text[0]) + text.Substring(1);. Inside Main print Helpers.Capitalize("hello").

Show example solution
Add the Capitalize method to Helpers. In Main write Console.WriteLine(Helpers.Capitalize("hello"));
Example solution:
using System;

static class Helpers
{
    public static string Capitalize(string text)
    {
        if (string.IsNullOrEmpty(text)) return text;
        return char.ToUpper(text[0]) + text.Substring(1);
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Ready");
        Console.WriteLine(Helpers.Capitalize("hello"));
    }
}

Test yourself

  1. What does Capitalize return?

    Helpers.Capitalize("hello")
    • "Hello"
    • "HELLO"
    • "hello"
    • "h"
    Show answer

    "Hello" — Correct. Only the first letter is uppercased: "Hello".

  2. Complete the Capitalize body

    return char.ToUpper(text[0]) + text.____(1);
    Show answer
    return char.ToUpper(text[0]) + text.Substring(1);
  3. Match each method to its behavior

    Capitalize
    Uppercases first letter
    ToUpper
    Uppercases a letter
    Substring
    Takes a portion
    IsNullOrEmpty
    Checks if empty

All lessons in Intermediate