User Tools

Site Tools


Strings in C#

Declaring and Initializing

// Simple examples.
string s1 = "This is a house.";
string s2 = @"C:\temp\readme.txt";
string s3 = String.Empty; // use String.Empty instead of ""
string s4 = "\u00C8pic"; // Èpic
// Repeat a sequence of characters.
string s1 = new String('-', 8);
string s2 = new String('o', 1000);
// Construct a string from a char array. 
char[] arr = { 'X', 'Y', 'Z' };
string s = new String(arr);
// Construct a char array from a string.
char[] arr = "Aardvark".ToCharArray();


// Get n characters at the beginning of a string.
string s = str.Substring(0, n);
// Get all characters starting from n (inclusive) to the end of a string.
string s = str.Substring(n);
// Remove n characters from the end of a string.
string s = str.Substring(0, str.Length-n);
// Remove 5 characters from a string starting from the index 3.
string str = "One*****Two";
string s = str.Remove(3, 5); // OneTwo
// Replace ";" with " | "
string str = "File;Open;New";
string s = str.Replace(";", " | "); // File | Open | New
// Insert a string ", " into another string at a specified position.
string str = "OneTwo";
string s = str.Insert(3, ", "); // One, Two
// Pad a string to a given length with a specified character.
string str = "ABC";
string s1 = str.PadLeft(8, '*');                // *****ABC
string s2 = str.PadLeft(8);                     //      ABC
string s3 = str.PadLeft(str.Length + 5, '-');   // -----ABC
string s4 = str.PadRight(str.Length + 5, '-');  // ABC-----
// Trim whitespaces.
string str = " \taaa\t\n   ";
string s1 = str.Trim(); // aaa
// Trim specified characters.
string str = "+-+abc+-+";
string s1 = str.Trim("+-".ToCharArray());      // abc
string s2 = str.TrimStart("+-".ToCharArray()); // abc+-+
string s3 = str.TrimEnd("+-".ToCharArray());   // +-+abc

Splitting and Joining

String.Split takes a string and returns an array of strings.

// By default, Split uses whitespace characters as delimiters.
string str = "aaa bbb\tccc\nddd";
string[] arr = str.Split(); // arr = { "aaa", "bbb", "ccc", "ddd" }
// Using an explicit delimiter.
string str = "aaa bbb ccc ddd";
string[] arr1 = str.Split(" ".ToCharArray());
string[] arr2 = str.Split(' ');
string[] arr3 = str.Split(new char[] { ' ' });
// Using multiple delimiters.
string str = "aa bb cc:dd:ee";
char[] delimiters = new char[] { ' ', ':' };
string[] arr = str.Split(delimiters);
// Using a string delimiter(s).
string str = "white-+-blue-green-+-purple";
string[] arr = str.Split(new string[1] { "-+-" }, StringSplitOptions.None);
    // arr = {"white","blue-green","purple"};
// Remove empty entries using StringSplitOptions.RemoveEmptyEntries.
string str = "aaa;;bbb;ccc";
string[] arr1 = str.Split(';'); // arr1 = { "aaa", "", "bbb", "ccc", }
string[] arr2 = str.Split(";".ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries); // arr2 = { "aaa", "bbb", "ccc" }

String.Join builds a new string by combining an array of strings.

string[] arr = {"One", "Two", "Three"};
string str = String.Join(";", arr); // str = "One;Two;Three"


// Obtain the index of the first occurrence of a given substring or a character in the string.
int i = str.IndexOf(s);
// Obtain the index of the first occurence of any character in a specified array of Unicode characters.
int i = str.IndexOfAny(new char[]{'@', '.', ',', '!'});
// Obtain the index of the last occurrence of a given substring or a character in the string.
int i = str.LastIndexOf(s);
// Obtain the index of the last occurence of any character in a specified array of Unicode characters.
int i = str.IndexOfAny(new char[]{'a', 'b', 'c'});
// By default the search methods perform a case-sensitive match using rules applicable to the current culture. 
// Perform a case-insensitive search: check if a string starts with a word 'the', 'The', 'THE', etc.
bool test = str.StartsWith("the", StringComparison.InvariantCultureIgnoreCase);


  • (equality comparison) Although strings are reference types, the equality operators are defined to compare the values of the strings rather than their references. Use an overload of the String.Equals method (or the == operator) to test whether two strings are equal.
  • (order comparison) Strings do not support < and > operators for comparisons. Use the static String.Compare or String.CompareOrdinal methods or the instance method CompareTo to sort strings. Do not use these methods to check for equality.
  • Ordinal comparisons interpret characters as Unicode codes. Culture-sensitive comparisons interpret characters using an alphabet.
  • The == operator and the instance version of Equals with no arguments always perform ordinal case-sensitive comparison. The CompareTo method performs culture-sensitive, case-sensitive order comparison.

In string comparison, specify the type of comparison using the StringComparison enum:

public enum StringComparison
    CurrentCulture, // case-sensitive
    InvariantCulture, // case-sensitive
    Ordinal, // case-sensitive

Example: Perform a case-insensitive comparison using the current culture:

Console.WriteLine(String.Compare("ala", "ALA", true)); // 0

Example: Perform a culture-sensitive, case-sensitive comparison:

Console.WriteLine("B".CompareTo("C")); // -1
Console.WriteLine("B".CompareTo("B")); // 0
Console.WriteLine("B".CompareTo("A")); // 1

Example: Display an integer that indicates the lexical relationship between two strings. Note that in some cases the ordinal comparison returns a number with an opposite sign than the culture-sensitive comparison. It means that the ordinal comparison and the culture-sensitive comparison may result in different sorting orders.

Console.WriteLine(String.Compare("aaa", "ZZZ", StringComparison.InvariantCultureIgnoreCase)); // -1
Console.WriteLine(String.Compare("aaa", "ZZZ", StringComparison.OrdinalIgnoreCase));          // -25
Console.WriteLine(String.Compare("aaa", "ZZZ", StringComparison.InvariantCulture));           // -1
Console.WriteLine(String.Compare("aaa", "ZZZ", StringComparison.Ordinal));                    // 7
Console.WriteLine(String.Compare("ZZZ", "aaa", StringComparison.InvariantCultureIgnoreCase)); // 1
Console.WriteLine(String.Compare("ZZZ", "aaa", StringComparison.OrdinalIgnoreCase));          // 25
Console.WriteLine(String.Compare("ZZZ", "aaa", StringComparison.InvariantCulture));           // 1
Console.WriteLine(String.Compare("ZZZ", "aaa", StringComparison.Ordinal));                    // -7


The CopyTo instance method copies a specified number of characters from a position in the string instance to a specified position in an array of Unicode characters.

public void CopyTo(
	int sourceIndex,
	char[] destination,
	int destinationIndex,
	int count

ASCII encoding

using System.Text // ASCIIEncoding
// Convert a string into an array of ASCII codes.
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] arr = ascii.GetBytes(str);
// Convert an array of ASCII codes into an array of characters.
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] arr = { 102, 45, 201, 34, 67, 83 };
char[] chars = ascii.GetChars(arr);
// Convert the byte[] array arr to a string.
string str = new System.Text.ASCIIEncoding().GetString(arr);
// Different ways to convert an ASCII code 65 (0x41) to a character ('A').
char ch = '\u0041';
ch = '\x0041';
ch = (char)65;


The System.Security.SecureString class represents text that should be kept confidential. The text is encrypted when being used, and deleted from computer memory when no longer needed.

Features of the SecureString class:

  • automatically encrypts its string value
  • the string value is assigned to a specific memory location
  • the garbage collector doesn't move the string around (no multiple copies)
  • the string is mutable but it can be made read-only when necessary
  • SecureString implements IDisposable allowing for controlled disposal of the string value

Because SecureString needs to be initialized, the initialization data is kept in memory. To minimize this risk, SecureString can deal with only individual characters at a time i.e. it's not possible to pass an entire string directly to SecureString.

Example: Read one character at a time from the user input and append it to the SecureString:

using System;
using System.Security;
using (SecureString str = new SecureString())
    Console.Write("Enter security key: ");
    ConsoleKeyInfo cki = Console.ReadKey(true);
    while (cki.Key != ConsoleKey.Enter)
        cki = Console.ReadKey(true);

The Marshal class offers methods that can be used when converting a SecureString to a normal string. Those methods accept a SecureString and return an IntPtr. Each method has a corresponding method that needs to be called to clear the internal buffer. For example, the SecureStringToGlobalAllocUnicode method has the corresponding ZeroFreeGlobalAllocUnicode method.

Example: Convert the SecurityString to a normal string:

using System;
using System.Security;
using System.Runtime.InteropServices; // Marshal
using (SecureString secureStr = new SecureString())
public static void ConvertToUnsecureString(SecureString secureStr)
    IntPtr str = IntPtr.Zero;
        str = Marshal.SecureStringToGlobalAllocUnicode(secureStr);
        // Make sure to remove the normal string from memory.
notes/csharp/strings.txt · Last modified: 2020/08/26 (external edit)