C# Strings Tutorial

In this tutorial we learn about the string data type. We cover how to create string literals, or by using the string constructor, string concatenations and string formatting functions.

We also list common properties and functions of the string class.

What is a string

In C# we have the benefit of the keyword string to combine single characters into words and sentences.

In fact, a string is actually an array of characters. In languages such as C, we can’t use a string. We have to explicitly define arrays of characters.

Example:
#include <stdio.h>
int main()
{
    char message[] = "Hello World";

    printf(message);

    return 0;
}

Even though the example above is a different language, we can see that the string Hello World has to be defined as an array of chars.

How to create a string object

In C# we have multiple ways to create a string object:

  • Assign a string literal to a String variable
  • Use a String class constructor
  • Use the string concatenation operator (+)
  • Use the string concatenation function
  • Retrieve a property or calling a method that returns a string
  • Call a formatting method to convert a value or an object to its string representation

Each of these will apply to the specific situation we need them in.

String literal

The most common method to create a string is to create a string literal. We do this by assigning a string value to a string variable.

Syntax:
string identifier = "value";
Example:
using System;

namespace Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            string message = "Hello World";

            Console.WriteLine(message);
            Console.ReadLine();
        }
    }
}

In the example above, we store our string in a variable.

String constructor

We can create a new string object with the string class constructor.

Example:
using System;

namespace Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            // char array
            char[] letters = { 'H', 'e', 'l', 'l', 'o' };

            // string of char array
            string greeting = new string(letters);

            Console.WriteLine(greeting);
            Console.ReadLine();
        }
    }
}

String concatenation

When multiple strings are combined (concatenated) it creates a new string. A string is concatenated with the + operator.

The compiler will concatenate a string when the + operator is used on strings, but will perform mathematical operations on numbers.

Example:
using System;

namespace Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName = "Peter";
            string lastName = "Parker";

            Console.WriteLine(firstName + " " + lastName);
            Console.ReadLine();
        }
    }
}

Function that returns a string

A new string is created when we return a string from a function. The new string can be stored in a variable or used directly.

Example:
using System;

namespace Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Message());
            Console.ReadLine();
        }

        static string Message()
        {
            return "Hello World";
        }
    }
}

In the example above, we use the newly created string directly in the WriteLine() function.

String formatting function

We can use any string formatting function, like the WriteLine() or Format() function, to create a string.

Example: writeline function
using System;

namespace Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName = "Bruce";
            string lastName = "Wayne";

            Console.WriteLine("Name: {0} {1}", firstName, lastName);
            Console.ReadLine();
        }
    }
}
Example: format function
using System;

namespace Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dob = new DateTime(1986, 08, 07);
            string formattedDob = String.Format("Date of Birth: {0:D}", dob);

            Console.WriteLine(formattedDob);
            Console.ReadLine();
        }
    }
}

A list of common properties of the String class

The following table shows some of the most commonly used properties of the String class.

PropertyDescription
CharsGets the Char object at a specified position in the current String object.
LengthGets the number of characters in the current String object.

A list of common methods of the String class

The following table shows some of the most commonly used functions of the String class.

FunctionDescription
Compare()Compares two specified string objects and returns an integer that indicates their relative position in the sort order.
Concat()Concatenates (combine) string objects.
Equals()Determines whether two specified String objects have the same value.
Format()Replaces one or more format items in a specified string with the string representation of a specified object.
IndexOf()Returns the zero-based index of the first occurrence of the specified Unicode character in the current string.
IndexOf()Returns the zero-based index of the first occurrence of the specified string in this instance.
Insert()Returns a new string in which a specified string is inserted at a specified index position in the current string object.
IsNullOrEmpty()Indicates whether the specified string is null or an Empty string.
Join()Concatenates all the elements of a string array, using a specified separator between each element.
Remove()Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string.
Replace()Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string.
Replace()Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string.
string[] Split()Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array.
ToLower()Returns a copy of this string converted to lowercase.
ToUpper()Returns a copy of this string converted to uppercase.
Trim()Removes all leading and trailing white-space characters from the current String object.

Summary: Points to remember

  • A string is a collection of ASCII characters that forms words and sentences.
  • In C#, we have several options to create a string.
    • The most common option is to initialize a string literal.
    • We can also create a string object with its class constructor.
    • Any time we combine more than one string, a new string is created.
    • Any function that returns a string will create a new string.
    • Any function that formats a string, like WriteLine() or Format() will create a new string from their inputs.