Strings

Strings are a sequence of characters, like so:

string myString = "Hello, World!";

Strings have a few important properties:

  • They are Unicode.
  • They are immutable.
  • They are reference types, but are treated like value types in use (e.g. when passed to a method, a copy is made).

A few different types of strings

Plain ol string

string myString = "Hello, World!";

This type of string is the most common. Some things you should know:

  • Adding a double quote within a string requires the use of the escape character \": string myString = "He said \"Hello\" to me.";
  • Adding a backslash within a string requires the use of the escape character \\: string myString = "The path is C:\\Program Files\\MyApp";
  • Adding a newline within a string requires the use of the escape character \n: string myString = "Hello\nWorld!";
  • Adding a tab within a string requires the use of the escape character \t: string myString = "Hello\tWorld!";

Verbatim string

string myString = @"Hello, World!";

This type of string is useful when you need to include special characters in a string without having to use the escape character.

  • Adding two double quotes within a string will result in a single double quote within the string: string myString = @"He said ""Hello"" to me.";
  • Backslashes are not treated as escape characters, so you can use them freely within the string: string myString = @"The path is C:\Program Files\MyApp";

Raw string

string myString = """Hello, World!""";

This type of string is useful when you need to include special characters in a string without having to use the escape character. In newer versions of C# and probably my favorite type of string.

String interpolation

string name = "Alice";
string greeting = $"Hello, {name}!";

This type of string is useful when you need to include variables within a string. My other favorite type of string!

You can combine string interpolation with verbatim strings:

string name = "Alice";
string greeting = $@"Hello, I say to ""{name}!""";

Empty strings - declaring them and checking for them

Common methods:

  • String.Empty: Represents an empty string. You can also declare an empty string like this: "" but Spencer recommends using String.Empty for consistency (also, he thinks double quotes everywhere looks ugly).
  • String.IsNullOrEmpty(): Checks if a string is null or empty.
  • String.IsNullOrWhiteSpace(): Checks if a string is null, empty, or consists only of white-space characters (like space or tab). (🌶️🌶️🌶️ This is Spencer's preferred method for checking if a string is empty.)

Common Methods/Properties

  • Length: Get the number of characters in a string.
  • String.Join(): Concatenate elements of an array into a single string.
  • ToLower() / ToUpper(): Convert strings to lowercase or uppercase.
  • Contains(): Check if a string contains a specified substring.
  • StartsWith() / EndsWith(): Determine if a string starts or ends with a specific substring.
  • Trim() / TrimStart() / TrimEnd(): Remove whitespace from the start, end, or both ends of a string.
  • Substring(): Extract a substring from a string.
  • IndexOf() / LastIndexOf(): Find the position of a substring within a string.
  • Replace(): Replace occurrences of a substring with another substring.
  • Split(): Split a string into an array of substrings based on a delimiter.

Quick mention of StringBuilder

StringBuilder is a mutable string type that is meant to be used when you need to build a long string in a loop. It is more efficient than using the + operator to concatenate strings.

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 1000; i++)
{
    sb.Append(i);
}

Console.WriteLine(sb.ToString());

I use this class surprisingly often,

Checking for equality

Strings can be compared in various ways, depending on your specific needs:

Basic Equality Checks

  • ==: Checks if two strings are the same.
  • !=: Checks if two strings are different.
  • Equals(): Checks if two strings are the same.

Case-Insensitive Comparisons

To compare strings without considering case differences:

string str1 = "Hello";
string str2 = "hello";
bool areEqual = string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase);

Best Practices

  • Use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for most programmatic string comparisons.
  • Avoid using == and != for string comparisons, as it doesn't allow specifying the comparison method.

Additional Resources: