C# Strings

  • Strings in C# are enclosed in double quotes
  • A string is a data type
  • A string is a collection of characters

You can manipulate strings in several ways; we will cover the most common ways. Create a new C# Console Application and name it Strings. Then between the code block type:

   static void Main(string[] args)
        {
            string name = "Asim";
            Console.WriteLine(name);
            Console.ReadLine();
        }

This is a simple string. We assigned the value “Asim” to the variable name, and then printed it out.

Escape Character

The escape character is useful for giving instructions or setting directories. Comment out string name =”Asim” and below it write:

  static void Main(string[] args)
        {
            //string name = "Asim";
            string File = "The document is located in: C:\users\Admin\Documents";
            Console.WriteLine(File);
            Console.ReadLine();
        }

Now if you copy that code and run it, it won’t work; you will get an “unrecognised escape sequence” error. This is because in C# the \ means escape the next character. There are two ways to fix this problem: The first way is to put double backslash \\ and the second is to use the @ symbol. This will escape the escape sequence process.

Example

   //string name = "Asim";
     string File = "The document is located in: C:\\users\\Admin\\Documents";
     Console.WriteLine(File);
     Console.ReadLine();

The first process can be time consuming and is not the best solution, so the second solution is a better choice.

   //string name = "Asim";
     string File = @"The document is located in: C:\users\Admin\Documents";
     Console.WriteLine(File);
     Console.ReadLine();

In this case you only need the @ in the beginning.

New Line

Making a new line is quite simple: all you do is use \n (backslash and n), which provides a new line feed.

Console.WriteLine ("This is a \n new line!");

Concatenation

Concatenation is joining two (or more) things together (in this case strings). To concatenate something in C#  you use the + sign.  Here is a simple concatenation:

Console.WriteLine(name + " Is 18 years old");

Take the variable name (which was created earlier) and then concatenate it to the sentence ”  Is 18 years old”.

String.Format

The string.format method formats a string. For example, in the UK the currency symbol is the pound sign (£) and in the USA it’s the dollar sign ($). You could write this by hand, for example Console.WriteLine (“Your balance is £5″), but the problem here is that if you gave the program away to someone in the USA or France, they would see the pound sign instead of their own currency symbol. This is where the .Net framework becomes useful, as it will automatically format the text depending on the user’s regional settings.

Example

int currency = 5;
string strFormat;

strFormat = string.Format("{0:C}", currency);

Now when you debug this, you will see it says £5, or the corresponding currency symbol for your country. This information is taken from the computer’s regional settings, and all this work is based on the .Net framework. The 0 in the format key means format the first parameter, and then after the colon you specify how you want to format it. You do not need to use the ToString() method, as String.Format is looking for a number to format anyway..

Example 2

 int currency = 5;
 int percentage = 25;
 string strFormat;

 strFormat = string.Format("{0:C} {1:P}", currency, percentage);

In this example there are two parameters: the first one (currency) is formatted with a pound sign and the second is formatted with a percentage symbol.

At times, large numbers such as 1 million are separated by commas or periods. To format numbers like this, in the above code just replace the “{0:C}” with 0:N. You can also print out a percentage, in this case it’s 0:P. Depending on your regional settings, the numbers will be separated by a comma or period.

Here are the common C# string operators:

Operator Description Example
\ Escape Character Console.WriteLine(“Asim Said: \”Welcome to thecodingguys\””);
@ Escapes the escape process Console.WriteLine(@”Go to: C:\Windows\System32\CMD.exe”);
\n New line Console.WriteLine(“Wow look a \n new line”);
\a Sound Beep Console.WriteLine(“What was that noise \a ?”);
{0:C} Currency Console.WriteLine(“{0:C}”, 5.00);
{0:N} Separate numbers but dot, or comma Console.WriteLine(“{0:N}”, 1000000);
{0:P} Percentage Console.WriteLine(“{0:P}”, 35);

Manipulating Strings

There are many built in methods available to manipulate strings; for example you might what to covert a string to upper-case or lower-case. In the following examples we will format strings in various ways, and are the common ways to format strings.

For these examples we are using a string variable called yourMessage with the value “Welcome to thecodingguys” and a finalResult variable set to null. For the sake of brevity we have omitted the Console.WriteLine(finalResult) and Console.ReadLine() from the examples.

string yourMessage = "Welcome to thecodingguys";
string finalResult = null;

ToUpper and ToLower

The ToUpper() and ToLower() methods convert the string’s case.

Example

 finalResult = yourMessage.ToLower();
 finalResult = yourMessage.ToUpper();

Replace

The replace method replaces a string. It takes two parameters, the old string and new string. It can also take chars.

 finalResult = yourMessage.Replace(" ", "-");

In this example we have replaced the spaces from “Welcome to thecodingguys” with dashes instead.

Output

Welcome-to-thecodingguys

Substring

The substring method can be used to return parts of a string. For example from the yourMessage variable we can return the first 5 characters only. The substring method takes two parameters: the start index and length index as integer.

finalResult = yourMessage.Substring(0, 7);

The 0 specifies the start point, in this case it is at the beginning. The 7 specifies how many characters we want from the starting point. To get all the characters you would do this:

finalResult = yourMessage.Substring(0, yourMessage.Length);

Output

Welcome

Exceptions: Watch out for the ArguementOutofRangeException which is common, and occurs when the string length is shorter than the points specified. For example if we put 0, 25 it would give that exception, as yourMessage is only 24 characters long.

Length

The length method counts how many characters there are in the string.

finalResult = yourMessage.Length.ToString();

Since finalResult is a data type of String, the ToString() method needs to be used to convert the integer to string.

There are many more methods available, however we cannot go through all of them. Below is a list of 3  more which may come in handy:

Method Description Output
Contains See if a string contains a certain piece of text Returns boolean (either true of false)
StartsWith See if a string starts with a certain piece of text Boolean – true of false
EndsWith See if a string ends with a certain piece of text Boolean – true of false.

Summary

This tutorial focued on formatting strings, string methods, and also manipulating strings.

Remember:

  • The escape character is backslash \
  • To escape the escape sequence use @
  • To concatenate two strings use +