C# Tutorial – String manipulation


Sometimes an application has to do a lot of string manipulation operations. Especially when it needs to print data in a well specified format. Sometimes it just needs to let user know something. In this post I’ll show you few techniques how to manipulate strings and explain what are consequences of using each.

String operations

Based on what you have learnt from the input and output streams tutorial you can write a simple interactive application. User greeting could look like:

string name = "Joe";
string greeting = "Hi " + name;

It demonstrates simple string concatenation, but string class is very powerful and has a lot of useful methods.

string greeting = "Hi " + name.ToUpper(); // Result: greeting = "Hi JOE"
greeting = greeting.Replace("Hi", "Hello");// Result: greeting = "Hello JOE"

Here you can check full list of System.String methods.

Strings are immutable

This is very important to understand that a string object is immutable – can’t change after it’s created. This means that in following example:

string txt = "AAA";
txt.Replace('A', 'B');

Will output:


Why? This is because Replace  method returns a new object. In order to see ‘BBB’ you have to assign result of replace operation to the variable:

txt = txt.Replace('A', 'B');

String format

Regular string operations are very powerful, but sometimes if one has to look at the code it’s not clear what the output might be. There is alternative method, let’s have a look at code below.

string greeting = string.Format("Message from {0}: Hi {1}, what a nice day!", myName, otherName);

You can intuitively say what is the greeting value. Now few details. The Format  method takes many parameters. The first one is format string which contains parameters in a form of {X}  where X is an index. Next to the format strings are parameters. They are indexed starting from 0 (as all indexes in C#). This way the first parameter after format string has index 0, the second – index 1, etc.

BTW, This format pattern is also supported in Console class:

Console.WriteLine("Message from {0}: Hi {1}, what a nice day!", myName, otherName);

Building a big / complicated string

There is one more way to build complicated strings. There is a special class called StringBuilder . It handles string operations in much more efficient way (details below).

StringBuilder message = new StringBuilder();
message.Append("Message from ");
message.Append(": ");
message.AppendFormat("Hi {0}, what a nice day!", otherName);

Note you have to call message.ToString()  method to get the actual string object.

Here you can find full list of StringBuilder methods.

How to choose a way to manipulate strings?

You now know how you can manipulate, but which method you should choose? There is no simple answer. It depends on what you want to do.

  • Simple manipulation – If you need to contactenate few strings (2-3) then the standard way is fine.
string item = "car";
string msg = "This " + item + " is available";

But you have to understand what is happening underneath. First, the application will concatenate “This “  and  item  and will create “This car”  string. Next it will concatenate it with  ” is available”  and create the final one: “This car is available” . This way it will create one unnecessary string (allocate memory, use it and free the memory). It’s fine for few strings, but it become more and more inefficient when you add more strings.

  • String formatting – Use for more complicated string operations.
string item = "car";
string when = "on Friday";
string msg = string.Format("This {0} is available {1}", item, when);

In this case the application will be able to compute output string size, allocate appropriate memory block upfront and fill with required chars.

  • StringBuilder – For complex string operations.

The class supports efficient string operations. It doesn’t allocate memory upfront, but holds reference to passed arguments. Only when ToString  method is called it composes the string. It’s a good choice when you operate on big strings or do a lot of string operations.


Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 thoughts on “C# Tutorial – String manipulation