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 Regula
Trang 1Chapter 12 Làm Việc Với String
Hoang Anh Viet
VietHA@it-hut.edu.vn
HaNoi University of Technology
1
Trang 2Mục Tiêu
“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 .”
Trang 3Roadmap
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
Trang 412.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
Trang 5String 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
Trang 6Alias and String Class
Alias
• In C#, the string keyword is an alias for String -> string and
String are equivalent
Trang 7Declaring 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
Trang 8// 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
Trang 9Immutability 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
Trang 10Immutability 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.
Trang 11Remark
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
Trang 1212 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
Trang 13
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";
string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";
//Output: "The olean Harp", by Samuel Taylor Coleridge
13
Trang 14Regular 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:
Trang 15string 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
Trang 16String Escape Sequences
\U Unicode escape sequence for surrogate pairs. \Unnnnnnnn
Trang 17Roadmap
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
Trang 1812.3 Định dạng Specifiers và toàn cầu hóa
Định dạng dữ liệu để hiển thị cho người dùng một cách cụ
Trang 19 Việc xây dựng trong số các đối tượng sử dụng định
dạng chuỗi số tiêu chuẩn hoặc tùy chỉnh các định dạng chuỗi số được xác định bởi NET Framework
19
Trang 20Format Strings
Định dạng chuỗi tiêu chuẩn thường có dạng Axx.
• Một là định dạng bạn muốn yêu cầu
• Và xx là một specifier tùy chọn chính xác.
Ví dụ về các định dạng cho specifiers số được.
• "C" cho đơn vị tiền tệ
• "D" cho thập phân
• "E" for scientific notation
• "F" cho các ký hiệu khoa học
• Và "X" để ký hiệu thập lục phân.
• "G" cho chung Đây là định dạng mặc định specifier, và cũng là
định dạng mà chúng tôi nhận được khi chúng tôi gọi Object.ToString.
• Suports một trong những chuỗi định dạng tuỳ chỉnh.
Trang 21class 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));
Trang 22 Vì vậy, nếu chúng ta gọi ToString System.Int32 một
ngày, chúng tôi sẽ có được một đại diện của chuỗi giá trị trong vòng
Trang 24Object.ToString, IFormattable
Tất cả được xây dựng trong số các loại cũng như ngày, thời gian thực hiện các loại giao diện này
Một đối tượng mà thực hiện các giao diện
IFormatProvider là-ngạc nhiên-một nhà cung cấp định dạng
Trang 25Roadmap
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
Trang 2612.4 Làm việc String từ nguồn Bên
ngoài
Lý do :
• Chúng tôi cần phải giao tiếp với thế giới bên ngoài bằng cách sử dụng một số hình thức mã hóa khác, như là UTF-8.
• Chúng tôi có thể sử dụng lớn các chuỗi Unicode về cuối nhỏ
hoặc dây về cuối nhỏ chút Unicode (Intel nền tảng)
NET Framework Làm cho công việc này chuyển đổi dễ dàng với các lớp System.Text.Encoding
[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Encoding : ICloneable
Trang 27Remark
Mã hóa là một quá trình chuyển đổi một tập các ký tự
Unicode vào một chuỗi các byte
Giải mã là đảo ngược, nó là quá trình chuyển đổi một chuỗi các byte được mã hóa thành một bộ ký tự
Trang 28Các tiêu chuẩn Unicode
UTF-8 Đại diện cho mỗi điểm mã là một chuỗi 1-4 byte.
UTF-16 Đại diện cho mỗi điểm mã là một chuỗi 1-2 16-bit số
nguyên
UTF-32 Đại diện cho mỗi điểm mã như là một số nguyên 32-bit
Trang 29cuối nhỏ byte được hỗ trợ
UTF32Encoding
Mã hóa ký tự bằng cách sử dụng Unicode UTF-32 mã hóa.
29
Trang 31Phương thức GetByte và GetByteCount
Phương thức GetByteCount xác định xem kết quả có
bao nhiêu bytes trong bảng mã Unicode
Phương thức GetBytes thực hiện việc mã hóa các ký tự trong xâu
Tương tự, phương thức GetCharCount xác định trong kết quả có bao nhiêu ký tự trong các bytes được mã
Trang 32string unicodeString = "This string contains the
unicode character Pi(\u03a0)";
// Tạo 2 kiểu mã khác nhau
Encoding ascii = Encoding.ASCII;
Encoding unicode = Encoding.Unicode;
//Chuyển đổi xâu đó vào trong một mảng byte[].
byte[ ] unicodeBytes =
unicode.GetBytes(unicodeString);
Example
Trang 33// Thực hiện việc chuyển đổi từ kiểu mã này sang kiểu mã
string asciiString = new string(asciiChars);
// Hiển thị chuỗi trước và sau khi chuyển đổi.
Console.WriteLine( "Original string: {0}", unicodeString);
Console.WriteLine("Ascii converted string: {0}",
Trang 34Nội Dung
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
Trang 35
12.5 StringBuilder
Lớp System.Text.StringBuilder có thể dùng để sửa đổi một xâu mà không cần tạo ra một đối tượng mới
Tại sao lại thế?
• Việc sử dụng StringBuider làm giảm bộ nhớ lưu trữ các xâu sau khi thực hiện việc sửa đổi mội chuỗi.
• Tăng hiệu suất khi liên kết nhiều xâu trong một vòng lặp
Chúng ta có thể tạo ra một thể hiện mới cho
StringBuilder bằng cách khởi tạo một biến với việc nạp chồng một phương thức khởi tạo
StringBuilder MyStringBuilder = new
StringBuilder("Hello World!");
35
Trang 36Thiết lập dung lượng và chiều dài xâu
Số lượng kí tự tối đa mà một StringBuilder có thể lưu trữ gọi là dung lượng tối đa cuẩ đối tượng đó
Phân biệt giữa dung lượng và chiều dài mà một
StringBuilder lưu dữ
StringBuilder MyStringBuilder = new
StringBuilder("Hello World!", 25);
Dung lượng của một StringBuider
Trang 37Thiết lập dung lượng và chiều dài xâu
về chiều dài thì thuộc tính về dung lượng không thể thay đổi
thay đổi giá trị giống như thuộc tính về chiều dài
lượng để thiết lập độ dài tối đa cho đối tượng mà ta
dùng
tra dung lượng của StringBuilder hiện tại.
hoặc thiết lập
MyStringBuilder.Capacity = 25;
37
Trang 38Chỉnh sửa một xâu StringBuilder
Bảng sau liệt kê các phương pháp để sửa đổi các nội dung của một
StringBuilder
StringBuilder.Append Thêm thông tin vào cuối của StringBuilder
Hiện tại StringBuilder.AppendF
ormat
Thay thế một định dạng xác định trong 1 xâu thông qua định dạng văn bản.
StringBuilder.Insert Chèn một chuỗi hoặc một đối tượng vào một
vị trí xác định trong StringBuilder hiện tại.
StringBuilder.Remove Xóa kí tự có chỉ số xác định trong
StringBuilder hiện tại.
StringBuilder.Replace Thay thế một kí tự tại một vị trí xác định
Trang 40 Phương thức AppendFormat sẽ thêm văn bản vào
cuối của StringBuilder.
Nó cũng thực thi giao diện IFormattable
int MyInt = 25;
StringBuilder MyStringBuilder = new
StringBuilder("Your total is ");
MyStringBuilder.AppendFormat("{0:C} ", MyInt);
Console.WriteLine(MyStringBuilder);
Kết quả : Your total is $25.00
Trang 41Insert
Phương thức Insert cho phép chèn một chuỗi hoặc 1 đối tượng vào vị trí xác định trong StringBuilder hiện tại
StringBuilder MyStringBuilder = new
StringBuilder("Hello World!");
MyStringBuilder.Insert(6,"Beautiful ");
Console.WriteLine(MyStringBuilder);
Kết quả : Hello Beautiful World!
41
Trang 42 The Remove method is used to remove a specified
number of characters from the current StringBuilder,
beginning at a specified zero-based index
StringBuilder MyStringBuilder = new
StringBuilder("Hello World!");
MyStringBuilder.Remove(5,7);
Console.WriteLine(MyStringBuilder);
Result: Hello
Trang 43StringBuilder MyStringBuilder = new
StringBuilder("Hello World!");
MyStringBuilder.Replace('!', '?');
Console.WriteLine(MyStringBuilder);
Result: Hello World?
43
Trang 44Regular Expression
Regular Expression enables to do the folowings:
• Creating, comparing, and modifying strings
• rapidly parsing large amounts of text and data to search for,
remove, and replace text patterns
Trang 45Roadmap
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
45
Trang 4612.6 Searching Strings with Regular
Expression.
The System.Text.RegularExpression.Regex class can
be used to search strings
These searches can range in complexity from very
simple to making full use of regular expressions
The static method Regex.IsMatch performs the search given the string to search and a string that contains the search pattern
For example:
Trang 48foreach (string s in numbers)
// Keep the console window open in debug mode.
System.Console.WriteLine( "Press any key to exit.");
System.Console.ReadKey();
} //end of main
}//end of TestRegularExpressionValidation
Trang 50Replacing Text with Regex
Using NET regular expressions via the Regex.Replace method overloads, we can replace text
For example:
Trang 51using System.Text.RegularExpressions;
public class EntryPoint {
static void Main(string[] args)
Regex regex = new Regex(pattern);
Trang 52 In this chapter, we have known:
• The string-handling capabilities of the NET Framework and C#
• Why the string is included in the base class library and why the CLR designers chose to annex it into the set of built-in types.
• How common string usage is Furthermore, the library
provides a thorough implementation of cultural-specific patterns, via CultureInfo.
• Can create our own cultures easily using the
CultureAndRegionInfoBuilder class.
• Gaven a brief tour of the regular-expression capabilities of
the NET Framework, even though a full treatment of the regularexpression language is outside the scope of this book
• The string and text-handling facilities built into the CLR, the
.NET Framework, and the C# language are welldesigned and easy to use.