DEV Community

Cover image for Beginner C#: Working with Strings
Sam Walpole
Sam Walpole

Posted on • Originally published at samwalpole.com

Beginner C#: Working with Strings

Now that you know some more about variables and different data types, we'll explore them in a bit more detail and learn some of the common things that you might want to do. In this post, we'll explore strings further and how to use them.

String concatenation

String concatenation is a fancy way of saying joining strings together. To join two strings together, use the + operator:

// Example 1
string concatenated = "String 1. " + "String 2.";
// concatenated = "String 1. String 2."

// Example 2
string string1 = "String 1. ";
string string2 = "String 2.";
string concatenated = string1 + string2;
// concatenated = "String 1. String 2."
Enter fullscreen mode Exit fullscreen mode

There is another string concatenation operator, +=. This allows the two strings to be concatenated and the new concatenated string to be assigned to the original variable. It is probably better demonstrated than described:

string string1 = "String 1. ";
string1 += "String 2.";
// string1 = "String 1. String 2."
Enter fullscreen mode Exit fullscreen mode

String interpolation

An interpolated string is a string that has other code expressions inside of it. These expressions are evaluated first to give the final string. This is useful for producing strings dynamically, as the value of the expression can change. An interpolated string is designated by putting a $ before the quotation marks, and the expression is placed inside curly braces.

// Example 1
string name = "Sam";
string interpolated = $"Hello, my name is {name}.";
// interpolated = "Hello, my name is Sam."

// Example 2
string interpolated = $"Sum: {5 + 6}";
// interpolated = "Sum: 11";
Enter fullscreen mode Exit fullscreen mode

N.B. The second example uses the integer addition operator, +, which we will cover in a later post.

Escaping characters

If you try including quotation marks (") within your string, you'll realise that it doesn't work because they are used to start and end strings. To include a quotation mark in your string, you have to escape it first. To do this, put a backslash (\) before the quotation mark (\"). There are a number of other escape sequences that are useful to know when using strings:

  • \" becomes "
  • \\ becomes \
  • \n becomes new line
  • \r becomes carriage return

For example:

string myQuote = "I like \"quotation marks\".";
// becomes I like "quotation marks".
Enter fullscreen mode Exit fullscreen mode

Verbatim strings

A verbatim string means that the string is printed exactly how you type it. This means any escape sequence is ignored and the actual characters are printed. For example, when talking about Windows file system paths, the backslashes need to be interpreted as actual backslashes and not escape sequences. A verbatim string is designated by starting the string with an @ symbol.

string regularString = "C:\\Users\Sam";
// throws an error due to unrecognised escape sequence

string verbatimString = @"C:\\Users\Sam";
// verbatimString = "C:\\Users\Sam"
Enter fullscreen mode Exit fullscreen mode

Formatting strings

Here we will come across our first method. We will cover methods in more detail in a later post, but they provide a way of performing an operation and returning some value. In this case, we will look at the string.Format method, which takes some parameters and returns a string.

string myString = string.Format("My name is {0} and I am {1} years old", "Sam", 27);
// myString = "My name is Sam and I am 27 years old";
Enter fullscreen mode Exit fullscreen mode

The above example demonstrates how string.Format works. Each expression within the parenthesises (()) is known as an argument. The first argument is the string that you want to be formatted. It contains curly braces and an index number, which will be replaced by the values in the later argument. Note that indexes start from 0, so {0} is replaced with "Sam" and {1} is replaced with 27.

However, the real power of the string.Format method is being able to format the values that you pass in to the arguments. For example:

string myString = string.Format("{0:C}", 12.345);
// myString = "$12.35"
// N.B. the currency symbol shown depends on your current culture settings

string myString = string.Format("{0:E}", 12345);
// myString = "1.234500E+004"
Enter fullscreen mode Exit fullscreen mode

These are just two examples, first formatting a number as currency and secondly formatting a number in scientific notation. The string.Format method is very powerful and there are so many other ways that you can format strings. Here are some other ways to format numbers and dates.

Check for empty strings

You will find that often you will need to check to see if a string contains any characters or not. For that we can use the string.IsNullOrEmpty method, which return true if it is empty or false if it is not empty.

bool isEmpty = string.IsNullOrEmpty("Hello");
// isEmpty = false

bool isEmpty = string.IsNullOrEmpty("");
// isEmpty = true

bool isEmpty = string.IsNullOrEmpty(string.Empty);
// isEmpty = true

bool isEmpty = string.IsNullOrEmpty(null);
// isEmpty = true
Enter fullscreen mode Exit fullscreen mode

Note that "" and string.Empty are equivalent. As well as being empty, a string can also be null. This is a special value and we will cover this properly in a later post, but for now, just know that string.IsNullOrEmpty returns true when the string is null.

Lowercase strings

Often when you need to compare two strings, you will convert both strings to lowercase so that any capitalisation isn't taken into account. For this reason, the ToLower method takes a string and returns the same string with all lowercase characters.

string myString = "Hello, my name is Sam.";
string lowercase = myString.ToLower();
// lowercase = "hello, my name is sam."
Enter fullscreen mode Exit fullscreen mode

Getting parts of a string

Sometimes you will need to get part of a string. For this reason, we can use the Substring method. The first argument of the method is the index of the original string to start at (remember indexes start at 0). There is a second optional argument for the index of the original string to stop at. If no second argument is provided, then the substring will continue to the end of the original string.

string fullString = "Hello, my name is Sam";

string subString = fullString.Substring(7);
// subString = "my name is Sam"

string subString = fullString.Substring(0, 5);
// subString = "Hello"
Enter fullscreen mode Exit fullscreen mode

Splitting and joining strings

Sometimes you will find that you need to split and join strings based on some rule. For example, you might want to split a string into individual words, or you might want to join strings with a comma (,) to make a CSV. This is where the Split and string.Join methods come into play.

string myString = "Hello, my name is Sam.";
string[] split = myString.Split(' ');
// split = ["Hello,", "my", "name", "is", "Sam."]
Enter fullscreen mode Exit fullscreen mode

There are a couple of things to note here. First the Split method takes a char as an argument, so we use apostrophes('). In this case, we're splitting by a space. Note that we could have also left the arguments empty because by default the Split method splits by spaces.

Secondly, we have a new data type here, string[]. This stands for an array of strings, which basically means a collection of multiple strings grouped together in one variable. We can access them by their index. For example:

string[] split = ["Hello,", "my", "name", "is", "Sam."];
string hello = split[0];
// hello = "Hello,"
Enter fullscreen mode Exit fullscreen mode

We will cover arrays in more detail in a later post.

The string.Join method basically does the opposite job of Split. It takes a char and an array of strings and returns a single string, with each part separated by that char.

string[] split = ["This", "is", "a", "string"];
string joined = string.Join(',', split);
// joined = "This,is,a,string"
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this post, we have gone through some of the most common operations and methods that you will need to know in order to work with strings. I would highly recommend practicing using these more so you get comfortable with how and when to use them. If you don't want to create a new Visual Studio project just to play around in, .NET Fiddle is a great online C# sandbox for quickly running small snippets of code.

To make sure that you don't miss any posts in this series, please follow this blog and subscribe to my newsletter. If you found this post helpful, please like it and share it. You can also find me on Twitter. If you are able to, please feel free to buy me a coffee. It helps support the writing that I do for the community. 😊


This post is part of a beginner C# series. I will update this section with links to each post when each new post is published.

  1. Why learn C#?
  2. Getting Started
  3. Variables and Basic Data Types
  4. Working with Strings

Top comments (0)