11/16/24, 10:57 PM C# in a Nutshell - Code Listings
Chapter 6 - .NET Fundamentals
String and Text Handling
Char
// char literals:
char c = 'A';
char newLine = '\n';
// [Link] defines a range of static methods for working with characters:
[Link] ([Link] ('c')); // C
[Link] ([Link] ('\t')); // True
[Link] ([Link] ('x')); // True
[Link] ([Link] ('x')); // LowercaseLetter
ToUpper & ToLower - and the Turkey bug
// ToUpper and ToLower honor the end-user’s locale, which can lead to subtle bugs.
// This applies to both char and string.
// To illustrate, let's pretend we live in Turkey:
[Link] = [Link] ("tr-TR");
// The following expression evaluates to false:
[Link] ([Link] ('i') == 'I');
// Let's see why:
[Link] ([Link] ('i')); // İ
// In contrast, the *Invariant methods always apply the same culture:
[Link] ([Link] ('i')); // I
[Link] ([Link] ('i') == 'I'); // True
Constructing strings
// String literals:
string s1 = "Hello";
string s2 = "First Line\r\nSecond Line";
string s3 = @"\\server\fileshare\[Link]";
// To create a repeating sequence of characters you can use string’s constructor:
[Link] (new string ('*', 10)); // **********
// You can also construct a string from a char array. ToCharArray does the reverse:
char[] ca = "Hello".ToCharArray();
string s = new string (ca); // s = "Hello"
[Link]();
Null and Empty Strings
// An empty string has a length of zero:
string empty = "";
[Link] (empty == ""); // True
[Link] (empty == [Link]); // True
[Link] ([Link] == 0); // True
//Because strings are reference types, they can also be null:
string nullString = null;
[Link] (nullString == null); // True
[Link] (nullString == ""); // False
[Link] ([Link] (nullString)); // True
[Link] ([Link] == 0); // NullReferenceException
Accessing Characaters within a string
string str = "abcde";
char letter = str[1]; // letter == 'b'
// string also implements IEnumerable<char>, so you can foreach over its characters:
foreach (char c in "123") [Link] (c + ","); // 1,2,3,
Searching within strings
// The simplest search methods are Contains, StartsWith, and EndsWith:
[Link] ("quick brown fox".Contains ("brown")); // True
[Link] ("quick brown fox".EndsWith ("fox")); // True
// IndexOf returns the first position of a given character or substring:
[Link] ("abcde".IndexOf ("cd")); // 2
[Link] ("abcde".IndexOf ("xx")); // -1
// IndexOf is overloaded to accept a startPosition StringComparison enum, which enables case-insensitive searches:
[Link] ("abcde".IndexOf ("CD", [Link])); // 2
[Link] w w .[Link]/nutshell/[Link] 1/4
11/16/24, 10:57 PM C# in a Nutshell - Code Listings
// LastIndexOf is like IndexOf, but works backward through the string.
// IndexOfAny returns the first matching position of any one of a set of characters:
[Link] ("ab,cd ef".IndexOfAny (new char[] {' ', ','} )); // 2
[Link] ("pas5w0rd".IndexOfAny ("0123456789".ToCharArray() )); // 3
// LastIndexOfAny does the same in the reverse direction.
Manipulating strings
// Because String is immutable, all the methods below return a new string, leaving the original untouched.
// Substring extracts a portion of a string:
string left3 = "12345".Substring (0, 3); // left3 = "123";
string mid3 = "12345".Substring (1, 3); // mid3 = "234";
// If you omit the length, you get the remainder of the string:
string end3 = "12345".Substring (2); // end3 = "345";
// Insert and Remove insert or remove characters at a specified position:
string s1 = "helloworld".Insert (5, ", "); // s1 = "hello, world"
string s2 = [Link] (5, 2); // s2 = "helloworld";
// PadLeft and PadRight pad a string to a given length with a specified character (or a space if unspecified):
[Link] ("12345".PadLeft (9, '*')); // ****12345
[Link] ("12345".PadLeft (9)); // 12345
// TrimStart, TrimEnd and Trim remove specified characters (whitespace, by default) from the string:
[Link] (" abc \t\r\n ".Trim().Length); // 3
// Replace replaces all occurrences of a particular character or substring:
[Link] ("to be done".Replace (" ", " | ") ); // to | be | done
[Link] ("to be done".Replace (" ", "") ); // tobedone
Splitting & Joining strings
// Split takes a sentence and returns an array of words (default delimiters = whitespace):
string[] words = "The quick brown fox".Split();
[Link]();
// The static Join method does the reverse of Split:
string together = [Link] (" ", words);
[Link](); // The quick brown fox
// The static Concat method accepts only a params string array and applies no separator.
// This is exactly equivalent to the + operator:
string sentence = [Link] ("The", " quick", " brown", " fox");
string sameSentence = "The" + " quick" + " brown" + " fox";
[Link](); // The quick brown fox
[Link] and Compostite Format Strings
// When calling [Link], provide a composite format string followed by each of the embedded variables
string composite = "It's {0} degrees in {1} on this {2} morning";
string s = [Link] (composite, 35, "Perth", [Link]);
[Link]();
// The minimum width in a format string is useful for aligning columns.
// If the value is negative, the data is left-aligned; otherwise, it’s right-aligned:
composite = "Name={0,-20} Credit Limit={1,15:C}";
[Link] ([Link] (composite, "Mary", 500));
[Link] ([Link] (composite, "Elizabeth", 20000));
// The equivalent without using [Link]:
s = "Name=" + "Mary".PadRight (20) + " Credit Limit=" + [Link] ("C").PadLeft (15);
[Link]();
Comparing strings
// String comparisons can be ordinal vs culture-sensitive; case-sensitive vs case-insensitive.
[Link] ([Link] ("foo", "FOO", [Link])); // True
// (The following symbols may not be displayed correctly, depending on your font):
[Link] ("ṻ" == "ǖ"); // False
// The order comparison methods return a positive number, a negative number, or zero, depending
// on whether the first value comes after, before, or alongside the second value:
[Link] ("Boston".CompareTo ("Austin")); // 1
[Link] ("Boston".CompareTo ("Boston")); // 0
[Link] ("Boston".CompareTo ("Chicago")); // -1
[Link] ("ṻ".CompareTo ("ǖ")); // 0
[Link] ("foo".CompareTo ("FOO")); // -1
// The following performs a case-insensitive comparison using the current culture:
[Link] ([Link] ("foo", "FOO", true)); // 0
// By supplying a CultureInfo object, you can plug in any alphabet:
[Link] w w .[Link]/nutshell/[Link] 2/4
11/16/24, 10:57 PM C# in a Nutshell - Code Listings
CultureInfo german = [Link] ("de-DE");
int i = [Link] ("Müller", "Muller", false, german);
[Link](); // 1
StringBuilder
// Unlike string, StringBuilder is mutable.
// The following is more efficient than repeatedly concatenating ordinary string types:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 50; i++) [Link] (i + ",");
// To get the final result, call ToString():
[Link] ([Link]());
[Link] (0, 60); // Remove first 50 characters
[Link] = 10; // Truncate to 10 characters
[Link] (",", "+"); // Replace comma with +
[Link]().Dump();
[Link] = 0; // Clear StringBuilder
Text Encodings and Unicode
[Link]();
// Call [Link] with a standard IANA name to obtain an encoding:
[Link] ([Link]);
Encoding chinese = [Link] ("GB18030");
[Link]();
// The static GetEncodings method returns a list of all supported encodings:
foreach (EncodingInfo info in [Link]())
[Link] ([Link]);
Encoding to byte Arrays
byte[] utf8Bytes = [Link] ("0123456789");
byte[] utf16Bytes = [Link] ("0123456789");
byte[] utf32Bytes = [Link] ("0123456789");
[Link] ([Link]); // 10
[Link] ([Link]); // 20
[Link] ([Link]); // 40
string original1 = [Link] (utf8Bytes);
string original2 = [Link] (utf16Bytes);
string original3 = [Link] (utf32Bytes);
[Link] (original1); // 0123456789
[Link] (original2); // 0123456789
[Link] (original3); // 0123456789
UTF-16 and SurrogatePairs
int musicalNote = 0x1D161;
string s = char.ConvertFromUtf32 (musicalNote);
[Link](); // 2 (surrogate pair)
char.ConvertToUtf32 (s, 0).ToString ("X").Dump(); // Consumes two chars
char.ConvertToUtf32 (s[0], s[1]).ToString ("X").Dump(); // Explicitly specify two chars
Dates and Times
Dates and Time Zones
Formatting and Parsing
Other Conversion Mechanisms
Working with Numbers
Enums
Tuples
The Guid Struct
Equality Comparison
Order Comparison
Utility Classes
[Link] w w .[Link]/nutshell/[Link] 3/4
11/16/24, 10:57 PM C# in a Nutshell - Code Listings
C# 12
in a Nutshell
About the Book
Code Listings
C# 12 in a Nutshell
C# 10 in a Nutshell
C# 9.0 in a Nutshell
C# 8.0 in a Nutshell
C# 7.0 in a Nutshell
Extras
Contact
Buy print or Kindle edition
Buy PDF edition
Read via O'Reilly subscription
[Link] w w .[Link]/nutshell/[Link] 4/4