Edit

Share via

Hello World - Introductory interactive tutorial

Do more with strings

You've been using a method, Console.WriteLine, to print messages. A method is a block of code that implements some action. It has a name, so you can access it.

Trim

Suppose your strings have leading or trailing spaces that you don't want to display. You want to trim the spaces from the strings. The Trim method and related methods TrimStart and TrimEnd do that work. You can just use those methods to remove leading and trailing spaces. Try the following code:

C#
string greeting = "      Hello World!       ";
Console.WriteLine($"[{greeting}]");

string trimmedGreeting = greeting.TrimStart();
Console.WriteLine($"[{trimmedGreeting}]");

trimmedGreeting = greeting.TrimEnd();
Console.WriteLine($"[{trimmedGreeting}]");

trimmedGreeting = greeting.Trim();
Console.WriteLine($"[{trimmedGreeting}]");

The square brackets [ and ] help visualize what the Trim, TrimStart and TrimEnd methods do. The brackets show where whitespace starts and ends.

This sample reinforces a couple of important concepts for working with strings. The methods that manipulate strings return new string objects rather than making modifications in place. You can see that each call to any of the Trim methods returns a new string but doesn't change the original message.

Replace

There are other methods available to work with a string. For example, you've probably used a search and replace command in an editor or word processor before. The Replace method does something similar in a string. It searches for a substring and replaces it with different text. The Replace method takes two parameters. These are the strings between the parentheses. The first string is the text to search for. The second string is the text to replace it with. Try it for yourself. Add this code. Type it in to see the hints as you start typing .Re after the sayHello variable:

C#
string sayHello = "Hello World!";
Console.WriteLine(sayHello);
sayHello = sayHello.Replace("Hello", "Greetings");
Console.WriteLine(sayHello);

Two other useful methods make a string ALL CAPS or all lower case. Try the following code. Type it in to see how IntelliSense provides hints as you start to type To:

C#
Console.WriteLine(sayHello.ToUpper());
Console.WriteLine(sayHello.ToLower());
Try the code in your browser