Working with Strings in C#

Strings in C# are defined as one or more characters that are used to represent text values. Strings are made up of any letter in the alphabet, numbers, or special characters, including #@!$%& and so forth. A string can contain one character or a whole paragraph. In this C# programming tutorial we are going to look at how to create strings, some common string methods, and string operators. By the end of this article, developers will have a firm understanding of how to work with strings and use them in their applications.

Before we begin, you should have an integrated development environment (IDE) or code editor that allows you to code in .Net or C# installed. Understanding the basics of C# data types is helpful as well. If you need a refresher, check out the companion article to this piece: C# Data Types. You can also brush up on C# for Beginners as well.

How Do You Create Strings in C#?

Defining C# string literals is pretty straightforward. All a developer needs to do is assign a value to the String data type, as shown in the following code:

 
using System;
 
public class StringExamples
{
            	public static void Main()
            	{
                            	string example1 = "A";
                            	string example2 = "Banana";
                            	string example3 = "This is a string as well, demonstrating using numbers 123 and symbols @#$%!";
                            	
                            	Console.WriteLine(example1);
                            	Console.WriteLine(example2);
                            	Console.WriteLine(example3);
            	}
}
 

If you run the above code, you will get the following result:

 
A
Banana
This is a string as well, demonstrating using numbers 123 and symbols @#$%!
 

The code works by creating three strings named example1, example2, and example3, respectively. We then assign a single character to example1, a word to example2, and a whole sentence that includes numbers and special characters to example3. We then use the ConsoleWriteLine() function to print out our three strings.

Console.WriteLine() is the function C# uses to print objects – which is really what a string is – to the user’s screen or console. It is one of the primary functions you will use when dealing with text values in your C# applications.

While displaying text and outputting text to the screen is a big part of working with strings, it is only one way you can use string data. In the next section we will look at some other functions you can use to manipulate text-based data and input.

Using the Escape Character in C#

There is an exception (or two) when it comes to what characters you can include in a string. Since we declare – or create – our strings by encasing them in between a set of quotation marks (” “), it makes sense that we cannot include them in a string – doing so confuses C#, as it does not know which set of quotation marks are intended to start and end the string.

There is a way to overcome this, fortunately. We can use an escape character or the backslash \ symbol prior to a double quote to ensure that C# sees it as just a regular character and not a signifier of the start or end of a string declaration.

Try out the following code to get a better understanding of how escape characters work in C#:

 
using System;
 
public class EscapeExample
{
            	public static void Main()
            	{
                            	string exampleEscape = "The man said \"Hello\".";
                            	
                            	Console.WriteLine(exampleEscape);
                            	
            	}
}
 

The output of this code is:

 
The man said "Hello".
 

If we had not used the escape character before each of our double quotes – used here to denote a quote of something someone said – our program would have ended with the following errors:

 
Compilation error (line 7, col 41): ; expected
Compilation error (line 7, col 46): ; expected
Compilation error (line 7, col 41): The name 'Hello' does not exist in the current context
Compilation error (line 7, col 46): Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
 

In addition to the \ escape character, C# offers other special characters that help to format text and strings, including:

  • \n : Newline escape to create a newline.
  • \r : Carriage return
  • \t : Tab to create a tab
  • \’ : An escape for single quote char
  • \” : An escape for double quotes in strings
  • \u: Unicode escape

Here is an example of using the backslash escape and the \t tab special character to insert tabs in a sentence:

 
using System;
 
public class EscapeExample
{
            	public static void Main()
            	{
                            	string exampleEscape = "The man said \"Hello\".";
                            	string exampleTab = "This \t is \t some \t tabs";
                            	
                            	Console.WriteLine(exampleEscape);
                            	Console.WriteLine(exampleTab);
            	}
}
 

Running this C# code in your IDE or code editor results in the following output:

 
The man said "Hello".
This  	is  	some      tabs
 

Finally, you can also escape a backslash as well – this is very useful if you need to represent filepaths, for example. To escape a backslash, you simply use another backslash in front of it. Try out the following code to see this practice in use:

 
using System;
 
public class EscapeExample
{
            	public static void Main()
            	{
 
                            	string example3 = "The file is located at: \\home\\user\\documents";
 
                            	Console.WriteLine(example3);
 
            	}
}
 

This program would result in:

The file is located at: \home\user\documents

How to use the verbatim Identifier on strings in Python

Another way to assign reserved special characters in strings is to bypass escape characters altogether, as they can become burdensome and error-prone if you have to use a lot of them. Instead, you can use the verbatim identifier – or @ symbol. Here is how the above code samples would look if we used the verbatim identifier in lieue of escape characters:

 
using System;
 
public class EscapeExample
{
            	public static void Main()
            	{
                            	string exampleEscape = @"The man said ""Hello"".";
                            	string example3 = @"The file is located at: \home\user\documents";
                            	
                            	Console.WriteLine(exampleEscape);
                            	Console.WriteLine(example3);
            	}
}
 

By adding the @ symbol before the values we are adding to our strings, we force C# to treat reserved special characters as regular characters. Note that, when we use verbatim identifiers for quoted text, we must double-up on our quotation marks surrounding the quoted text, as in the example3 string:

string exampleEscape = @"The man said ""Hello"".";

Running our previous code example would result in:

The man said "Hello".
The file is located at: \home\user\documents

The verbatim identifier can be used for much more than a replacement for escape characters. We can also use it to create multiline strings. Multiline strings are formatted strings that, when output, will be displayed on more than one line. When using verbatim identifiers to create multiline strings, you declare your string in the following manner:

using System;

namespace ExampleMultiline {

class MultiLineSample {

static void Main(string[] args) {
string multiExample = @"The man walked,
Blindly forward
Then bumped into a tree.";

Console.WriteLine(multiExample);
}
}
}

Running this in your code editor or integrated development environment would result in:

 
The man walked,
     	Blindly forward
     	Then bumped into a tree.

A final note on the verbatim identifier: it can also be used to escape certain reserved keywords, including for, if, and public. However, that topic is beyond the scope of this article. For now, just be aware that verbatim identifier serves many purposes in C#

Joining Strings and String Concatenation in C#

A common function when dealing with strings is to join one or more together. This is known as concatenation. There are several methods a developer can use to concatenate strings in C# and we will be looking at a few of them in this section.

String Concatenation Operator or + Operator

The first method involves using the C# string concatenator operator – also known as the + operator. It is a pretty simple operator to use, as exhibited in the following code that shows how to join strings in C# with the concatenator operator:

 
using System;
 
public class ConcatenationExample
{
            	public static void Main()
            	{
                                            	
                            	string firstName = "James";
                            	string lastName = "Payne";
                            	
                            	string fullName = "My name is " + firstName + " " + lastName;
                            	
                            	Console.WriteLine(fullName);
            	}
}
 

In this code, we create two separate strings: firstName and lastName. We assign each a value and then create a third string called fullName, which we assign the value of some “My name is “. We then append – or concatenate – the additional values of firstName and lastName. This make the full value of fullName equal to “My name is James Payne”. We this when we execute the last line of our code, which is a WriteLine statement whose purpose is to write the value of fullName to the screen. When you run this code in your code editor, you get the result:

My name is James Payne

C# String Interpolation

Another way to join strings in C# is to use string interpolation. This method requires a developer to place the $ symbol at the beginning of the variable assignment, as shown in the example below:

 
using System;
 
public class ConcatenationExample2
{
            	public static void Main()
            	{
                                            	
                            	string firstName = "James";
                            	string lastName = "Payne";
 
                            	string fullName = $"{firstName} {lastName} is my name.";
                            	Console.WriteLine(fullName);
                            	
            	}
}
 

Using string interpolation is the preferred method to join strings in C#. Part of this has to do with issues that can arise when you use loops and the string concatenation operator together, which can lead to some issues with looping logic.

The result of this code is that it prints the text: “James Payne is my name” to the screen.

String.Concate Method in C#

C# has a method that is specifically designed to concatenate strings – the string.concate method. It can join strings, string objects, and arrays of strings or a combination of those types, into a string. Here is how it looks in code:

using System;
 
public class ConcatenationExample3
{
            	public static void Main()
            	{
                                            	
                            	string firstName = "James";
                            	string lastName = "Payne";
            	
                            	string fullName = string.Concat(firstName, lastName);
                            	Console.WriteLine(fullName);
                            	
            	}
}

Running this code in your C# IDE will output: “JamesPayne”. Note the lack of a space between the two joined strings. You will need to account for this in your programs if you opt to use the string.Concat method.

Converting Strings to Uppercase in C#

There are times when a developer needs to convert the case of a string from uppercase to lowercase or vice versa. There are many reasons for this: for form validation, to make processing data easier, and so forth. C# has several built-in methods that can help change the case of a string. We will look at two of them in this section.

To convert an entire string to uppercase, we use the C# String.ToUpper() method. Here is some sample code showing it in action:

using System;
 
public class UpperExample
{
            	public static void Main()
            	{
                                            	
                            	string fullName = "James Payne";
                            	
                            	Console.WriteLine(fullName);
                            	string upperMyName = fullName.ToUpper();  
                            	Console.WriteLine(upperMyName);
 
            	}
}

In this example, we start by creating a variable called fullName and assign it a value. Next, we use Console.WriteLine() to write “James Payne” to the screen. We do this to show the current case of fullName, which is a mix of upper and lower. Next, we create a new variable called upperMyName and assign it the value of fullName. Before it gets assigned though, the ToUpper() method gets applied to the value of fullName, which causes the text to become capitalized. Finally, we write the value of upperMyName to the screen to show that the value has, indeed, become uppercase. The result of running this program in your IDE would be:

James Payne
JAMES PAYNE

We can also directly convert a variable to uppercase in a print statement, as in the following example:

using System;
 
public class UpperExample2
{
            	public static void Main()
            	{
                                            	
                            	string fullName = "James Payne";
                            	
                            	Console.WriteLine(fullName);
                            	Console.WriteLine(fullName.ToUpper()); 
                            	Console.WriteLine(fullName);
 
            	}
}

When we run this code, we see that the variable fullName starts out as a mix of upper and lower case text. We then use the ToUpper() function in a print statement to convert the text to all uppercase for a single instance. This means that our string is not actually changed, but, instead, a single instance of it is created. This is showcased in the next line of code, which once more prints the value of fullName, which demonstrated that the value is still a mix of upper and lowercase letters. Here is the result of running this code:

James Payne
JAMES PAYNE
James Payne

Converting Strings to Lowercase in C#

Converting strings to lowercase in C# works the same way as converting them to uppercase, except that developers must use the String.ToLower() method instead of the String.ToUpper method. Here is an example of lowercase string conversion in C#:

using System;
 
public class LowerExample
{
            	public static void Main()
            	{
                                            	
                            	string fullName = "James Payne";
                            	
                            	Console.WriteLine(fullName);
                            	string upperMyName = fullName.ToLower();  
                            	Console.WriteLine(upperMyName);
 
            	}
}

Likewise, we can also directly convert a string to lowercase by applying ToLower() to a print statement:

using System;
 
public class LowerExample2
{
            	public static void Main()
            	{
                                            	
                            	string fullName = "James Payne";
                            	
                            	Console.WriteLine(fullName);
                            	Console.WriteLine(fullName.ToLower()); 
                            	Console.WriteLine(fullName);
 
            	}
}

String Methods and Functions in C# and .Net

We have only just touched the surface when it comes to the ways we can work with strings in C# and .Net. We will continue to look at other C# string methods and functions that let developers work with text-based data and string data types in the coming weeks, so be sure to check back often for more C# programming tutorials.

Read: Working with C# Math Operators.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read