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 Perl 5
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 Chapter 6 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 = ...
Get C# in a Nutshell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.