Đối tượng string• Đối tượng string có thể chuyển sang C-String string s = “ABCDEFG”; const char* cs = s.c_str; Hàm c_str trả ra dạng const char*... Đối tượng strings6 = “ABCD *F GHIJK”;
Trang 1Lập trình hướng đối tượng
Bài 9: String
Trang 2Giới thiệu
• Chuỗi (string) là danh sách các ký tự
– c string
– c++ string class
• Thí dụ: “hello”, “high school”, “H2O”.
• Các phép toán trên chuỗi gồm:
– Cộng: “high”+“school”=“highschool”
– So sánh: “high”<“school” // alphabetical
– Tìm kiếm/truy cập/biến đổi/xóa/chèn các chuỗi con
trong chuỗi đã cho
Trang 3 Trong C, chuỗi là một mảng ký tự được kết thúc đặc biệt hay một con trỏ ký tự
Nếu là mảng ký tự, phần tử cuối cùng của mảng là ‘\0’ để báo hiệu kết thúc chuỗi
Ở thí dụ trên str[] có chiều dài là 5:
str[0]=‘h’ str[1]=‘i’ str[2]=‘g’ str[3]=‘h’ str[4]=‘\0’
Mảng như trên có thể được khai báo như sau:
– char str[5] = {‘h’,’i’, ‘g’,’h’,’\0’};
Nếu viết char str[4] = {‘h’,’i’, ‘g’,’h’}; thì str là mảng 4 ký
tự chứ không phải là chuỗi.
Với char *p=“high”; hệ thống cung cấp bộ nhớ cho 5 ký tự
và lưu trữ từ “high” trong 4 phần tử đầu và ‘\0’ trong phần
tử thứ 5.
Trang 4C++ String
• C++ có thư viện <string>
• Trong thư viện này, lớp string được khai báo và thể hiện
• Chương trình sử dụng lớp string cần viết:
#include <string>
using namespace std;
string x(“high school”);
string x= “high school”;
Trang 5string s = “AB C DEFG”;
getline(cin, s); //reads entire line of characters into s
char c = s[2]; //assigns ‘C’ to c
Trang 6C++ String
– Không nhất thiết phải kết thúc bằng null
– string không phải là con trỏ mà là lớp
– Nhiều hàm thành phần với tham số vị trí bắt đầu và chiều dài
• Nếu đối chiều dài quá lớn, giá trị max được chọn
Trang 7Tạo đối tượng string
#include <string>
//string initialization
string s; //s contains 0 characters
string s1( "Hello" ); //s1 contains 5 characters
string s2 = “Hello”; //s2 contains 5 characters
//implicitly calls the constructor
string s3( 8, 'x' ); //s3 contains 8 'x' characters
string s4 = s3; //s4 contains 8 'x' characters
string s5(s2, 3, 2); //s5 copies a substring of s2; it contains ” lo ”
Trang 8Đối tượng string
• Đối tượng string có thể chuyển sang C-String
string s = “ABCDEFG”;
const char* cs = s.c_str();
Hàm c_str() trả ra dạng const char*
Trang 9Đối tượng string
cout << s.length() << endl;
In ra 4 với chuỗi s == “Leon”
Có thể sử dụng toán tử subscript operator [ ] để truy cập các subscript operator
ký tự đơn lẻ:
Thí dụ s[0] = ‘N’ ; //where index: 0 to length-1
Trang 10Đối tượng string
If(s2 < s5) cout << “s2 lexicographically precedes s5 \n”;
while(s4==s3) //…
So sánh theo thứ tự từ điển B>A
Đối tượng string có thể sử dụng các phép toán so sánh như
các dạng dữ liệu thông thường:
Thứ tự mẫu: ‘A’,”Apple”, “Banana”, “Zest”, ‘a’, “apricot”, “leon”
Trang 11Đối tượng string
Trang 12Đối tượng string
Trang 13Đối tượng string
s6 = “ABCD *F GHIJK”;
Hàm erase() và replace():
replace 2 characters from s6, starting at index 5, with “xyz”
Trang 14Đối tượng string
string s7 = “Mis si ssippi River basin”; //23 characters
cout << s7.find(“ si ”) << endl; //prints 3 cout << s7.find(“ so ”) << endl; //prints string::npos , 4,294,967,295
find() function
Trang 16• Range-checking
– s3.at( index );
• Returns character at index
• Can throw an out_of_range exception out_of_range
– [] has no range checking
Trang 18– returns positive if s1 is lexicographically greater
• compares letter by letter
• 'B' lexicographically greater than 'A‘
• ‘a’ lexicographically greater than ‘A‘
• ‘a’ lexicographically greater than ‘Z‘
– returns negative if less; zero if equal
• Sample order: ‘A’,”Apple”, “Banana”, “Zest”, ‘a’, “apricot”, “leon”
– s1.compare(start, length, s2, start, length)
• Compare portions of s1 and s2
Trang 20Hoán đổi chuỗi
• s1.swap(s2);
– Switch contents of two strings
Trang 21Các tính chất của chuỗi
• Các hàm thành phần
– s1.size() and s1.length()
• Number of characters in a string
Trang 22Tìm chuỗi con hay ký tự trong chuỗi
• Find functions
– If found, index returned
– If not found, string::npos returned
• Public static constant in class string
– s1.find( s2 )
– s1.rfind( s2 )
• Searches right-to-left
– s1.find_first_of( s2 )
• Returns first occurrence of any character in s2
• Example: s1.find_first_of( "abcd" )
Trang 23Tìm chuỗi con hay ký tự trong chuỗi
Trang 24Thay thế các ký tự trong chuỗi
• begin: index in s1 to start replacing
• N: number of characters to replace
• s2: replacement string – s1.replace( begin, N, s2, index, num )
• index: element in s2 where replacement comes from
Trang 25Thí dụ
s1.replace( begin, N, s2, index, num )
• begin: index in s1 to start replacing
• N: number of characters to replace
• s2: replacement string
• index: element in s2 where replacement comes from
• num: number of elements to use when replacing
string str = "this is an example string .";
string str3="sample phrase ";
str replace(19,6, str3 , 7, 6); // " , 7, 6); // " this is an example phrase . "
Trang 26Chèn các ký tự vào chuỗi
• s1.insert( index, s2 )
– Inserts s2 before position index
• s1.insert( index, s2, index2, N );
– Inserts substring of s2 before position index
– Substring is N characters, starting at index2
Trang 27Chuyển sang dạng char*
• Conversion functions
– Strings are not necessarily null-terminated
– s1.copy( ptr, N, index )
• Copies N characters into the array ptr
• Starts at location index
• Need to null terminate
Trang 28Chuyển sang dạng char *
Trang 29Cảnh báo
• Không chuyển đổi từ int hoặc char
– Các câu lệnh sau có thể gây ra lỗi hoặc chỉ cảnh báo (warning) nhưng có thể làm đổ vỡ chương trình sau đó
Trang 30Luồng chuỗi (String Stream)
• I/O của chuỗi tới và từ bộ nhớ
– Được gọi là vào/ra trong bộ nhớ hay xử lý luồng chuỗi
– Các lớp
• istringstream // input from string
• ostringstream // output to a string
• stringstream( string ) // most useful
• Cho phép dùng chuỗi như 1 file bên trong
• Hữu dụng cho việc tạo bộ đệm vào/ra
Trang 31Dịch vụ như một tuyến vào chuỗi vô danh mà có thể
ostringstream ostringstream oss ;
int n = 44;
float x = 3.14;
oss << "Hello!\t" << n << '\t' << x;
cout << endl << s << endl;
Luồng chuỗi ra
Trang 32const string buffer = oss.str();
istringstream istringstream iss iss (buffer);
cout << "y = " << y << endl;
Luồng chuỗi vào
Trang 33while( in.getline( buffer, 1024 ) ){
string stemp( buffer );
cout << "Line is:" << stemp << endl;
#1.34 2.99 1.4 8.99
• Example Output:
Line is:1.0 2.0 1,2
Line is:1.1 2.4 1.1,2.4
Line is:1.8 2.8 1.8,2.8
Line is:#1.34 2.99 Line is:1.4 8.99 1.4,8.99
Trang 34while( in.getline( buffer, 1024 ) ){
string stemp( buffer );
cout << "Line is:" << stemp << endl;
ifstream in( s1.c_str() );
string buffer;
while( getline( in, buffer ) ){
cout << "Line is:" << buffer << endl;
Trang 35Method Use
append(char *pt);
append(char *pt, size_t count);
append(string &str, size_t
Appends characters to a string from C-style strings, char's or other string objects
subscript operator, [], in that bounds are checked
copy(char *cstring, size_t count,
erase(iterator first, iterator last);
erase(iterator it);
Trang 36Method Use
find(char ch,size_t offset = 0);
find(char *pt,size_t offset = 0);
find(string &str,size_t offset =
insert(size_t pos, char *ptr);
insert(size_t pos, string &str);
insert(size_t pos, size_t count,
char ch);
insert(iterator it, InputIterator
start, InputIterator end);
Inserts characters at the specified position
replace(size_t pos, size_t count,
replace(iterator first, iterator
Replaces elements in a string with the specified characters The range can be specified by a start position and a number of elements to replace, or by using iterators