O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 = ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required