Tải bản đầy đủ (.ppt) (52 trang)

Chapter12 - Working with String potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (511.87 KB, 52 trang )

Chapter 12. Working With String
Hoang Anh Viet

HaNoi University of Technology
1
MicrosoftMicrosoft
Objectives
2
“Describes how strings are a first-class type in the CLR and
how to use them effectively in C#. A large portion of the chapter
covers the string-formatting capabilities of various types in
the .NET Framework and how to make your defined types
behave similarly by implementing IFormattable. Additionally, I
introduce you to the globalization capabilities of the framework
and how to create custom CultureInfo for cultures and regions
that the .NET Framework doesn’t already know about.”
MicrosoftMicrosoft
Roadmap
12 .1 String Overview
12.2 String Literals
12.3 Format Specifiers and Globalization
12.4 Working String from Outsite Sources
12 5 StringBuilder
12.6 Searching Strings with Regular Expression.
.
3
MicrosoftMicrosoft
12.1 String Overview

In C#, String is a built-in type.


In the built-in type collection , String is a reference type and but
most of the built-in types are value types.
4
MicrosoftMicrosoft
String Basics

A string is an object of type String whose value is text.

The text is stored as a readonly collection of Char objects.

Each of which represents one Unicode character encoded in UTF-
16.

There is no null-terminating character at the end of a C# string
(unlike C and C++). therefore a C# string can contain any number
of embedded null characters ('\0').

The length of a string represents the number of characters
regardless of whether the characters are formed from Unicode
surrogate pairs or not.
5
MicrosoftMicrosoft
Alias and String Class
6

Alias

In C#, the string keyword is an alias for String -> string and
String are equivalent.


String Class

The String class provides many methods for

Creating strings

Manipulating strings

Comparing strings.

It overloads some operators to simplify common string
operations.
MicrosoftMicrosoft
Declaring and Initializing Strings

We can declare and initialize strings in various ways, as shown in
the following example:
// Declare without initializing.
string message1;
// Initialize to null.
string message2 = null;
// Initialize as an empty string.
// Use the Empty constant instead of the literal "".
string message3 = System.String.Empty;
//Initialize with a regular string literal.
string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";
7
// Use System.String if we prefer.
System.String greeting = "Hello World!";
// In local variables (i.e. within a method body)

// you can use implicit typing.
var temp = "I'm still a strongly-typed System.String!";
// Use a const string to prevent 'message4' from /
/ being used to store another string value.
const string message4 = "You can't get rid of me!";
// Use the String constructor only when creating
// a string from a char*, char[], or sbyte*. See
// System.String documentation for details.
char[] letters = { 'A', 'B', 'C' };
string alphabet = new string(letters);
Declaring and Initializing Strings
8
MicrosoftMicrosoft
Immutability of String Objects

String objects are immutable: they cannot be changed after
they have been created.

All of the String methods and C# operators that appear to
modify a string actually return the results in a new string
object.

For example:
string s1 = "A string is more ";
string s2 = "than the sum of its chars.";
// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;
System.Console.WriteLine(s1);

// Output: A string is more than the sum of its chars.
9
MicrosoftMicrosoft
Immutability of String Objects

Note:

When create a reference to a string, and then "modify" the
original string, the reference will continue to point to the original
object instead of the new object that was created when the string
was modified.

For example:
string s1 = "Hello ";
string s2 = s1;
s1 += "World";
System.Console.WriteLine(s2);
//Output: Hello
10
MicrosoftMicrosoft
Remark

When we declare a string in your C# code, the compiler creates a
System.String object for us.

And then it places into an internal table in the module called the
intern pool.

The compiler first checks to see if we’ve declared the same string
elsewhere, and if we have, then the code simply references the one

already interned.
11
MicrosoftMicrosoft
Roadmap
12 .1 String Overview
12.2 String Literals
12.3 Format Specifiers and Globalization
12.4 Working String from Outsite Sources
12 5 StringBuilder
12.6 Searching Strings with Regular Expression.
.
12
MicrosoftMicrosoft
12.2 String Literals

Use regular string literals when we must embed escape characters
provided by C#.

For example:
string columns = "Column 1\tColumn 2\tColumn 3";
//Output: Column 1 Column 2 Column 3
string rows = "Row 1\r\nRow 2\r\nRow 3";
/* Output:
Row 1
Row 2
Row 3
*/
string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";
//Output: "The olean Harp", by Samuel Taylor Coleridge
13

MicrosoftMicrosoft
Regular and Verbatim String Literals

Use verbatim strings for convenience and better readability when
the string text contains backslash characters, for example in file
paths.

Verbatim strings use the delaration preceded with the @ character

For example:
14
string filePath = @"C:\Users\scoleridge\Documents\";
//Output: C:\Users\scoleridge\Documents\
string text = @"My pensive SARA ! thy soft
cheek reclined
Thus on mine arm, most soothing sweet it is
To sit beside our Cot, ";
/* Output:
My pensive SARA ! thy soft cheek reclined
Thus on mine arm, most soothing sweet it
is
To sit beside our Cot,
*/
string quote = @"Her name was ""Sara.""";
//Output: Her name was "Sara."
Example
15
MicrosoftMicrosoft
String Escape Sequences
Escape

sequence
Character name Unicode
encoding
\' Single quote 0x0027
\" Double quote 0x0022
\\ Backslash 0x005C
\0 Null 0x0000
\a Alert 0x0007
\b Backspace 0x0008
\f Form feed 0x000C
\n New line 0x000A
\r Carriage return 0x000D
\U
Unicode escape sequence for surrogate pairs.
\Unnnnnnnn
\u Unicode escape sequence \u0041 = "A"
\v Vertical tab 0x000B
16
MicrosoftMicrosoft
Roadmap
12 .1 String Overview
12.2 String Literals
12.3 Format Specifiers and Globalization
12.4 Working String from Outsite Sources
12 5 StringBuilder
12.6 Searching Strings with Regular Expression.
.
17
MicrosoftMicrosoft
12.3 Format Specifiers and

Globalization

Format the data to display to users in a specific way.

Dealing with these sorts of issues

Handling formatting of values,so on.

For example:

Display a floating-point value representing some tangible
metric in exponential form or

Display in fixed-point form.
18
MicrosoftMicrosoft
Format Strings

A format string is a string whose contents can be determined
dynamically at runtime.

We create a format string by using

Using the static Format method

Embedding placeholders in braces that will be replaced by other
values at runtime.

The built-in numeric objects use the standard numeric format strings
or the custom numeric format strings defined by the .NET

Framework.
19
MicrosoftMicrosoft
Format Strings

The standard format strings are typically of the form Axx.

A is the desired format requested

And xx is an optional precision specifier.

Examples of format specifiers for numbers are

"C" for currency

"D" for decimal

"E" for scientific notation

"F" for fixed-point notation

And "X" for hexadecimal notation

"G" for general. This is the default format specifier, and is also
the format that we get when we call Object.ToString.

Suports one of the custom format strings.
20
class FormatString
{

static void Main()
{
// Get user input.
System.Console.WriteLine("Enter a number");
string input = System.Console.ReadLine();
// Convert the input string to an int.
int j;
System.Int32.TryParse(input, out j);
// Write a different string each iteration.
string s;
for (int i = 0; i < 10; i++)
{
// A simple format string with no alignment formatting.
s = System.String.Format("{0} times {1} = {2}", i, j, (i * j));
System.Console.WriteLine(s);
}
//Keep the console window open in debug mode.
System.Console.ReadKey();
Console.Read();
}
}
Example
21
MicrosoftMicrosoft
Object.ToString, IFormattable

Every object derives a method from System.Object called ToString.

It’s extremely handy to get a string representation of our object for
output.


The default implementation of ToString merely returns the type of
the object itself.

We need to implement our own override to do anything useful.

Thus, if we call ToString on a System.Int32,we’ll get a string
representation of the value within.
22
MicrosoftMicrosoft
Object.ToString, IFormattable

But we want the string representation in hexadecimal format.

In fact, there is a way to get a string representation of an object by
implementing the IFormattable interface.
public interface IFormattable
{
string ToString( string format, IFormatProvider
formatProvider )
}
23
MicrosoftMicrosoft
Object.ToString, IFormattable

All built-in numeric types as well as date-time types implement this
interface.

An object that implements the IFormatProvider interface is—
surprise—a format provider.

24
MicrosoftMicrosoft
Roadmap
12 .1 String Overview
12.2 String Literals
12.3 Format Specifiers and Globalization
12.4 Working String from Outsite Sources
12 5 StringBuilder
12.6 Searching Strings with Regular Expression.
.
25

×