Skip to content

C# Strings 👷🏼‍♂️👷🏼‍♀️

verbatim -> @"Verbatim string, which can include linefeeds, etc."

Concatenation string myString = "a" + 5; // returns "a5" - calls .ToString() on the 5

However, better to use the StringBuilder class for lots of concatenations.

Comparison == applies to value of string (not to its reference)
< and > not allowed. Need to use CompareTo()

s.IndexOf(‘a’);      // returns first position of ‘a’ (or -1 if not found)
s.IndexOf(‘a’, i);   // returns first position of ‘a’ from position i onwards
s.Substring(start , count); // returns the next count characters from string s, starting at position start

Trimming characters from a String

string MyString = "{Hello World!}";
MyString = MyString.Trim(new Char[] { '{', '}' });

This can be used to remove chars from any point within the string (not just the end). Other methods on String can be more specific, e.g.

MyString.TrimStart( [char array] )
MyString.TrimEnd( [char array] )

Formatting

Console.WriteLine("{0}, {1}!", "Hello", "World");

Chars

\' \" \\ \0 \u or \x can be used to specify unicode chars, e.g.

char copyrightSymbol = '\u00A9';
char omegaSymbol = '\u03A9';

Conversion char to unsigned short is implicit. All other conversions must be explicit.

Strings

Arrays