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

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.

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