Beginner C#: Working with Strings

String concatenation

// Example 1
string concatenated = "String 1. " + "String 2.";
// concatenated = "String 1. String 2."

// Example 2
string string1 = "String 1. ";
string string2 = "String 2.";
string concatenated = string1 + string2;
// concatenated = "String 1. String 2."
string string1 = "String 1. ";
string1 += "String 2.";
// string1 = "String 1. String 2."

String interpolation

// Example 1
string name = "Sam";
string interpolated = $"Hello, my name is {name}.";
// interpolated = "Hello, my name is Sam."

// Example 2
string interpolated = $"Sum: {5 + 6}";
// interpolated = "Sum: 11";

Escaping characters

  • \” becomes “
  • \\ becomes \
  • \n becomes new line
  • \r becomes carriage return
string myQuote = "I like \"quotation marks\".";
// becomes I like "quotation marks".

Verbatim strings

string regularString = "C:\\Users\Sam";
// throws an error due to unrecognised escape sequence

string verbatimString = @"C:\\Users\Sam";
// verbatimString = "C:\\Users\Sam"

Formatting strings

string myString = string.Format("My name is {0} and I am {1} years old", "Sam", 27);
// myString = "My name is Sam and I am 27 years old";
string myString = string.Format("{0:C}", 12.345);
// myString = "$12.35"
// N.B. the currency symbol shown depends on your current culture settings

string myString = string.Format("{0:E}", 12345);
// myString = "1.234500E+004"

Check for empty strings

bool isEmpty = string.IsNullOrEmpty("Hello");
// isEmpty = false

bool isEmpty = string.IsNullOrEmpty("");
// isEmpty = true

bool isEmpty = string.IsNullOrEmpty(string.Empty);
// isEmpty = true

bool isEmpty = string.IsNullOrEmpty(null);
// isEmpty = true

Lowercase strings

string myString = "Hello, my name is Sam.";
string lowercase = myString.ToLower();
// lowercase = "hello, my name is sam."

Getting parts of a string

string fullString = "Hello, my name is Sam";

string subString = fullString.Substring(7);
// subString = "my name is Sam"

string subString = fullString.Substring(0, 5);
// subString = "Hello"

Splitting and joining strings

string myString = "Hello, my name is Sam.";
string[] split = myString.Split(' ');
// split = ["Hello,", "my", "name", "is", "Sam."]
string[] split = ["Hello,", "my", "name", "is", "Sam."];
string hello = split[0];
// hello = "Hello,"
string[] split = ["This", "is", "a", "string"];
string joined = string.Join(',', split);
// joined = "This,is,a,string"

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store