Utilizor
Contact Us

C# Strings

Working with text.

C# Strings

Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

string greeting = "Hello";

String Length

A string in C# is actually an object, which contain properties and methods that can perform certain operations on strings. For example, the length of a string can be found with the Length property.

String Methods

There are many string methods available, for example ToUpper() and ToLower(), which returns a copy of the string converted to uppercase or lowercase.

String Interpolation

Another option of string concatenation, is string interpolation, which substitutes values of variables into placeholders in a string. Note that you do not have to worry about spaces, like with concatenation:

string firstName = "John";
string lastName = "Doe";
string name = $"My full name is: {firstName} {lastName}";

Examples

String Length

Getting the length of a string.

using System;

class Program
{
  static void Main(string[] args)
  {
    string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    Console.WriteLine("The length of the txt string is: " + txt.Length);
  }
}

ToUpper and ToLower

Converting string case.

using System;

class Program
{
  static void Main(string[] args)
  {
    string txt = "Hello World";
    Console.WriteLine(txt.ToUpper());   // Outputs "HELLO WORLD"
    Console.WriteLine(txt.ToLower());   // Outputs "hello world"
  }
}

String Concatenation

Joining strings with +.

using System;

class Program
{
  static void Main(string[] args)
  {
    string firstName = "John ";
    string lastName = "Doe";
    string name = firstName + lastName;
    Console.WriteLine(name);
  }
}

String Interpolation

Using $ syntax for formatting strings.

using System;

class Program
{
  static void Main(string[] args)
  {
    string firstName = "John";
    string lastName = "Doe";
    string name = $"My full name is: {firstName} {lastName}";
    Console.WriteLine(name);
  }
}

Access Characters

Accessing characters by index.

using System;

class Program
{
  static void Main(string[] args)
  {
    string myString = "Hello";
    Console.WriteLine(myString[0]);  // Outputs "H"
    Console.WriteLine(myString[1]);  // Outputs "e"
  }
}