C# strings and formatting
A C# string is an immutable sequence of characters, so methods such as Substring, Replace, and ToUpper return new strings. Split turns a string into an array, string.Join does the reverse, and Trim and PadLeft change the white space around the text. StringBuilder is the right tool for building a long string in a loop, because it does not copy the text on every append.
C#
using System;
using System.Text;
class Program {
static void Main() {
string name = "Programonic";
Console.WriteLine(name.Length + " " + name.Substring(0, 7) + " " + name.IndexOf('m'));
Console.WriteLine(name.ToUpper() + " " + name.Replace("o", "0"));
string[] parts = "a,b,,c".Split(',');
Console.WriteLine(parts.Length + " " + string.Join("-", parts));
Console.WriteLine(" padded ".Trim().PadLeft(8, '*'));
Console.WriteLine("apple" == "APPLE");
Console.WriteLine(string.Equals("apple", "APPLE", StringComparison.OrdinalIgnoreCase));
double price = 1234.56;
Console.WriteLine(FormattableString.Invariant($"{price:F2} {price:N0} {42:D5} {255:X}"));
var builder = new StringBuilder();
for (int i = 1; i <= 3; i++) {
builder.Append(i).Append(i < 3 ? "," : "");
}
Console.WriteLine(builder);
}
}