Chapter 6. String Handling
C# offers a wide range of string-handling features. Support is provided
for both mutable and immutable strings, extensible string formatting, locale-aware
string comparisons, and multiple string encoding systems. The string handling
support also includes regular expression matching and replacement capabilities
based on Perl5 regular expressions, including lazy quantifiers (??, *?, +?, {n, m}?), positive and negative look-ahead, and conditional evaluation.
This chapter introduces and demonstrates the most common types you’ll
use in working with strings. The types mentioned
in this section all exist in the System, System.Text,
or System.Text.RegularExpressions namespaces (unless otherwise stated).
String Class
A C# string represents an immutable sequence of characters,
and aliases the System.String class. Strings have comparison,
appending, inserting, conversion, copying, formatting, indexing, joining,
splitting, padding, trimming, removing, replacing, and searching methods.
The compiler converts addition (+) operations on operands,
in which the left operand is a string to Concat() methods
(assuming it can’t fold the concatenation together directly at compile
time), and also preevaluates and interns string constants where possible (see Section 6.1.3 later in this chapter).
Comparing Strings
Although System.String is a reference type, the =
= operator
is overloaded, so you can easily compare two strings by value, as follows:
string a = "abracadabra"; string b = ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access