一、string概述
string是一個字符串的類,它集成的操作函數足以完成大多數情況下的需要。我們甚至可以把它當作C++的基本數據類型。
頭文件:#include <string>
注意:string.h和cstring都不是string類的頭文件。這兩個頭文件主要定義C風格字符串操作的一些方法,如strcpy() 、strlen()等。string.h是C語言頭文件格式,而cstring是C++頭文件格式,但是它和string.h是一樣的,它的目的是爲了和C語言兼容。
二、C++字符串和C字符串的轉換
C++提供的由C++字符串轉換成對應的C字符串的方法:data() 、c_str() 、copy()。需要注意的是,C++字符串並不以'\0'結尾。
1、data()
data() 是以字符數組的形式返回字符串的內容,但是並不添加'\0'。
2、 c_str()
c_str()返回一個以'\0'結尾的字符數組。c_str() 語句可以生成一個const char*指針,並且指向空字符的數組。這個數組的數據是臨時的,當有一個改變這些數據的成員函數被調用後,其中數據就會失效。故要麼現用現轉換,要麼把它的數據複製到用戶自己可以管理的內存中後在轉換。
string str = "Hello, I am LiMing.";
const char* cstr = str.c_str();
cout << cstr << endl;
str = "Hello, I am Jenny";
cout << cstr << endl;
改變了str的內容,cstr的內容也隨之改變,可以考慮把數據複製出來解決問題。
char *cstr = new char[20];
string str = "Hello, I am LiMing.";
strncpy(cstr, str.c_str(), str.size());
cout << cstr << endl;
str = "Hello, I am Jenny";
cout << cstr << endl;
使用strncpy函數將內容進行復制,這樣可以保證cstr中的內容不會隨着str的改變而改變。
3、 copy()
copy()是把字符串的內容複製到或寫入既有的c_string或者字符數組中。
copy(p, n, size_type _Off = 0):表明從string類型對象中至多複製n個字符到字符指針p指向的空間中,並且默認從首字母字符開始,也可以指定開始的位置(從0開始計數),返回真正從對象中複製的字符。不過用戶要確保p指向的空間足夠來保存n個字符。
size_t length;
char buf[8];
string str("Hello, I am LiMing.");
cout << str << endl;
length = str.copy(buf, 7, 3);
cout << "length:" << length << endl;
buf[length] = '\0';
cout << "str.copy(buf, 7, 5), buf contains:" << buf << endl;
cout << "buf len :" << strlen(buf) << endl;
length = str.copy(buf, str.size(), 3);
cout << "length:" << length << endl;
buf[length] = '\0';
cout << "str.copy(buf, str.size(), 5), buf contains:" << buf << endl;
cout << "buf len :" << strlen(buf) << endl;
三、string和int的轉換
1、使用sstream
//int 轉 string
int a_1 = 99;
string str_1;
stringstream ss;
ss << a_1;
ss >> str_1;
cout << "a_1:" << a_1 << endl;
cout << "str_1:" << str_1 << endl;
//string 轉 int
int a_2;
string str_2 = "12345";
ss.clear();//清除ss中的數據
ss << str_2;
ss >> a_2;
cout << "str_2:" << str_2 << endl;
cout << "a_2:" << a_2 << endl;
2、使用既有的函數
//string 轉 int
string str_3 = "54321";
int a_3 = stoi(str_3);
cout << "str_3:" << str_3 << endl;
cout << "a_3:" << a_3 << endl;
//int 轉 string
int a_4 = 54321;
string str_4 = to_string(a_4);
cout << "a_4:" << a_4 << endl;
cout << "str_3:" << str_3 << endl;
四、其他函數
int capacity() const; //返回當前容量,即string中不必增加內存即可存放的元素的個數
int max_size() const; //返回string對象中可存放的最大字符串長度
int size() const; //返回當前字符串大小
int length() const; //返回當前字符串長度
bool empty() const; //當前字符串是否爲空
void resize(int len, char c); //把當前字符串大小置爲len,並用字符c填充不足的部分。