Common String Tasks

Combine string methods to do everyday jobs, cleaning up input, reformatting names and phone numbers, padding, reversing and building long strings.

Apprentice · C# · Updated

By

After this lesson you can

  • Clean up and reformat text by combining string methods

Key takeaways

  • Trim the ends and pick one case, as in typed.Trim().ToLower(), before you compare or store what people type.
  • To reformat text, take it apart with Replace, Substring or Split, then put the pieces back together with interpolation.
  • Check optional parts, such as a middle name, before you add them, so you don't leave a double space.
  • PadLeft and PadRight add characters until a string reaches a length: "42".PadLeft(6, '0') gives 000042.
  • To build a string from many pieces in a loop, use a StringBuilder instead of +=, then call ToString() at the end.

Working with text is an everyday job for most developers. Data arrives from people typing, from databases, from files and from other programs, and you rarely control its format. Usually you need to tidy it into the format your program expects. These are the jobs you'll do most often, each built from the methods in the last lesson.

Clean up what people type

People add spaces and capital letters at random. Trim the ends and pick one case before you compare or store:

string typed = "  GEORGIA ";
string team = typed.Trim().ToLower();

Console.WriteLine(quot;[{team}]");
Console.WriteLine(team == "georgia");
[georgia]
True

Reformat a phone number

Take out everything that isn't a digit, then put the pieces back in the format you want:

string typed = "(614) 555-0182";
string digits = typed.Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "");

string formatted = quot;{digits.Substring(0, 3)}-{digits.Substring(3, 3)}-{digits.Substring(6)}";
Console.WriteLine(digits);
Console.WriteLine(formatted);
6145550182
614-555-0182

Turn a name around

Split a name into words, then rearrange them:

string fullName = "Samuel Black";
string[] names = fullName.Split(' ');

string lastFirst = quot;{names[1]}, {names[0]}";
string userName = quot;{names[0]}.{names[1]}".ToLower();

Console.WriteLine(lastFirst);
Console.WriteLine(userName);
Black, Samuel
samuel.black

Only add what's there

Some parts are optional, such as a middle name. Check before you add them, so you don't leave a double space:

Console.WriteLine(FullName("Glen", "", "Williamson"));
Console.WriteLine(FullName("Glen", "Carter", "Williamson"));

string FullName(string first, string middle, string last)
{
    if (middle == "")
    {
        return quot;{first} {last}";
    }
    return quot;{first} {middle} {last}";
}
Glen Williamson
Glen Carter Williamson

Pad to a width

PadLeft and PadRight add characters until a string reaches a length. Order numbers and receipts use them:

Console.WriteLine("42".PadLeft(6, '0'));
Console.WriteLine("Total".PadRight(10, '.') + "$12.50");
000042
Total.....$12.50

Reverse a string

A string can't change, so reverse its characters in an array and make a new string from it:

string word = "stressed";
char[] letters = word.ToCharArray();
Array.Reverse(letters);
string reversed = new string(letters);

Console.WriteLine(reversed);
desserts

Build a long string: StringBuilder

Because strings never change, text += ... in a loop makes a brand-new string every time. For a few joins that's fine. For hundreds, use a StringBuilder, which grows one piece of text in place, then turns it into a string at the end:

using System.Text;

StringBuilder html = new StringBuilder();
html.Append("<ul>");

string[] teams = { "Georgia", "Alabama", "Ohio State" };
foreach (string team in teams)
{
    html.Append(quot;<li>{team}</li>");
}

html.Append("</ul>");
Console.WriteLine(html.ToString());
<ul><li>Georgia</li><li>Alabama</li><li>Ohio State</li></ul>

using System.Text; at the top of the file lets you write StringBuilder without its full name, System.Text.StringBuilder.

Do it: make an order code for the team store

The team store prints a code on every order so the warehouse can find it. The code is the team's first three letters in capitals, a dash, then the order number with zeros in front to make 6 digits. The team names come from a form, so some have extra spaces or small letters.

The method gets two values:

  • team: the team's name as it was typed, a string (" georgia "). Once the spaces are trimmed, every name has at least 3 letters.
  • orderNumber: the order's number, an int (42).

For example, order 42 for " georgia ":

Step Here
The team, trimmed "georgia"
Its first 3 letters, in capitals "GEO"
The order number as text "42"
Padded on the left with zeros to 6 characters "000042"
The two, joined with a dash "GEO-000042"

So OrderCode(" georgia ", 42) returns "GEO-000042".

Your job: write the method OrderCode(string team, int orderNumber) so it returns the code, a string.

  • Trim the spaces from both ends of the team's name before you take its letters.
  • Take its first 3 letters, in capitals.
  • Turn the order number into text, and pad it on the left with 0s to 6 characters.
  • A number that already has 6 digits gets no zeros: 123456 stays 123456.
  • Join the letters and the digits with a dash, -.

Practiced live on the lesson page: write the C# right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Most string work is a short chain of the same few methods: trim, change case, find, cut, split, join. Learn to see a messy piece of text as those steps, and you can reshape almost anything.

Key terms

Cheat sheets