C-SHARP - 4.6 String Advanced

This video deepens our knowledge of strings in C#. The keyword string is an alias of the String class of the .NET framework: every string is an object. Reminder: strings are immutable, so calling a method on one always returns a brand-new string instead of mutating the original. Below is a tour of the most useful methods grouped by purpose.

Formatting and search

  • ToLower() / ToUpper(): return a copy in lower or upper case.
  • Trim(): removes spaces at the beginning and the end (not the ones inside the string).
  • IndexOf(value) / LastIndexOf(value): return the first or last index of a substring, or -1 if not found.
  • Substring(start) / Substring(start, length): extract a portion of the string.
  • Replace(old, new): replace a character or substring; the second overload returns the modified copy.
  • Split(separator): cuts the string into a string[] using a separator.
  • string.IsNullOrEmpty(s) and string.IsNullOrWhiteSpace(s): check if the string is empty (the second also considers whitespace as empty).
string s = "I am going to the gym.";
int idx = s.IndexOf("gym");
string copie = s.Substring(idx);
string remplace = s.Replace('a', 'o');
string[] mots = s.Split(' ');

int prix = 3199;
string monetaire = prix.ToString("C");   // currency format

Substring is a overloaded method: one version takes only a starting index, another takes a starting index and a length, which is handy for notification previews that show only the first part of a long message. To convert a string to a number we can use int.Parse or the safer Convert.ToInt32 which returns 0 on an empty input instead of throwing. Conversely number.ToString() turns a number into a string, with an optional format such as "C" for currency. In the next video we apply all of these methods on Visual Studio.