C#: Working With Strings

As promised in one of my earlier articles, I am back with an article entirely dedicated to Strings in C#. This article explains what strings in C# are and how they are created and formatted. We shall also see some different methods used for string manipulation. Finally, we will take a look at the string builder type which is an alternative to normal strings. So let the fun begin!

What are Strings?

Simply put, strings are a sequence of characters arranged to form some text. The character can be an alphabet letter, a number, or any special character. Strings store textual data. For instance, strings can be used to store the name and address of a person.

Creating Strings in C#

There are multiple ways to create strings in C#, and I will be explaining three most commonly used methods.

  1. Creating a string literal and assigning it to a string variable.
  2. Using String class constructor.
  3. Using String concatenation operator.

Have a look at the following code sample to see how the three mentioned methods are used for string creation in C#.

string FirstName = "Jeremy";
char[] name = { 'S', 'h', 'a', 'n', 'k', 's' };
string LastName = new string(name);
string FullName = FirstName + LastName;

Console.WriteLine(FirstName);
Console.WriteLine(LastName);
Console.WriteLine(FullName);

The above code snippet displays three different methods of creating strings in C#. In the first method, a string variable “FirstName” is declared and the string literal “Jeremy” is assigned to it. The second method seems bit complex. However, it is pretty simple. Just create an array of characters and pass it as a parameter to the String class constructor. This returns a string composed of the characters in the array. The string variable “LastName” has been initialized via the second method. Finally, you can also create strings by joining

two strings via the concatenation (+) operator. The variable “FullName” is assigned the string combination of string values in “FirstName” and “LastName” variables.

String Formatting

Raw or unformatted strings are harder to read. For instance, if you want to specify the price of some item, it is not convenient to write “99”. Rather formatting price as “$99” immediately tells the reader that this is the price of some item. Similarly, it is better to express percentages as “80%” rather than a simple 80.

To format strings in c#, the “string.Format” method is used. The method takes two parameters. First one is the string which contains indexes for the actual string values. The next parameters are string literals or variables. These literals or variables replace indexes in the first parameter. The index for the string is defined inside opening and closing braces. The format is also defined inside these braces.

For instance {1:0.0} specifies that this index should contain the value of the second parameter and it should be formatted as having at least one decimal value. This might sound a bit daunting at first, but the following example is going to make this clear. Take a look at it.

string Name = "Toyota";
int Price = 5000;
DateTime DateOfPurchase = new DateTime(2016, 2, 3);

string result = string.Format("{0} car purchased for {1:C} in {2:yyyy}", name, price, DateOfPurchase);

Console.WriteLine(result);

In the above example a string literal “Toyota” is stored in a variable “Name”. Similarly, an integer 5000 is stored in string variable “Price”. And finally, a DateTime object is being stored in the “DateOfPurchase” variable.

We want to create a string which includes these three string variables with proper formatting. We want to add a dollar sign before price and we want to extract year out of DateTime variable DateOfPurchase.

To do so, we use “string.Format” function. Have a look at its parameters the first one is a string. Pay particular attention to {0}, {1:C} and {2:yyyy}. These are the indexes, and they specify formatting as well. The second parameter “Name” will replace {0} in the first parameter. Similarly third parameter “Price” will replace {1:C} index. Here “C” specifies that this should be displayed with currency symbol. Finally, the fourth parameter “DateOfPurchase” replaces {2:yyyy}. Here “yyyy” signifies that only extract year from this date.

The output of this code snippet will look like this:  Toyota car purchased for $5,000.00 in 2016

String Functions

String functions are methods used to manipulate strings. C# comes with a myriad of built-in functions that can be used to alter the behavior of strings. With string functions, you perform tasks such as comparing two strings, getting the length of the string, getting a substring from a string, obtaining the index of a particular character, joining two strings and so on and so forth.

Take a look at the following example to see some of these functions in action.

string myString = "Marry had a little lamb";

Console.WriteLine(myString.ToUpper());
Console.WriteLine(myString.ToLower());
Console.WriteLine(myString.Equals("Marry had a little lamb"));
Console.WriteLine(myString.IndexOf("r"));
Console.WriteLine(myString + " Little Lamb");
Console.WriteLine(myString.Contains("lamb"));

The output for the above code sample will look like this:

MARRY HAD A LITTLE LAMB
marry had a little lamb
True
2
Marry had a little lamb Little Lamb
True

String Builder in C#

Strings in C# are immutable. This means that the value once stored inside a string type variable cannot be changed. For instance, if you have a string which contains “Marry”, you cannot append the string “Had a little Lamb” to it.  You must be wondering then why on earth we use concatenation operator “+” or concat function?  Concatenation operator simply joins two strings to form a new string. It doesn’t alter memory occupied by the strings being joined.

What if you need a mutable string? The answer to this question is the StringBuilder class in C#. StringBuilder is a mutable alternative to native strings. Values once stored in a StringBuilder type variable can be altered as many times as you want. Following example illustrates this concept.

StringBuilder sb = new StringBuilder();
sb.Append("Marry");
sb.AppendLine();
sb.Append("Had a little lamb.");

string text = sb.ToString();

Console.WriteLine(text);

In above example, a StringBuilder object “sb” is initialized. The “Append” method adds some content to the object. Now, if you want to add some more content to the string, you can do so via “Append” method. To get string text from the StringBuilder class, simply call ToString function on the object.

Note: StringBuilder is located in the System.Text namespace so you will need to add using System.Text; for the code above to work.

The output for the StringBuilder code above will look like this:

Marry
Had a little lamb.

This article provides a brief overview of some the most fundamental concepts related to String and StringBuilder classes in C#. I showed you how different ways of creating strings, how to format a string, how to use various string methods and how to use StringBuilder class for creating a mutable string. If you found this article helpful be sure to check out my C# Roadmap..