一、字符串的定義與賦值
C++中使用string庫來定義字符串變量,可以通過賦值運算符或者構造函數進行賦值。例如:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str1 = "hello world!";
cout << str1 << endl; //輸出 hello world!
string str2;
str2 = "i am a string.";
cout << str2 << endl; //輸出 i am a string.
string str3("c++ string");
cout << str3 << endl; //輸出 c++ string
return 0;
}
二、字符串的拼接與比較
使用加號運算符進行字符串的拼接,使用== 或者!= 運算符進行字符串的比較。例如:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str1 = "hello";
string str2 = "world!";
string str3;
str3 = str1 + " " + str2;
if(str3 == "hello world!")
cout << "str3 等於 hello world!" << endl;
return 0;
}
三、字符串的截取與查找
使用substr函數可以實現對字符串的截取操作,通過find函數可以定位字符串中某一字符或者子串出現的位置。例如:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str1 = "hello world!";
string subStr = str1.substr(6, 5); //截取子串:world
int pos = str1.find("o"); //定位字符 o 第一次出現的位置
cout << subStr << endl;
cout << pos << endl;
return 0;
}
四、字符串與C風格字符串的轉換
由於C++標準庫中string類型與C語言中的字符串表達不同,因此在C++開發中有時需要進行二者的轉換,例如:
#include <string>
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str1 = "hello world!";
const char* cstr = str1.c_str();
char cstrArray[20];
strcpy(cstrArray, cstr);
cout << cstrArray << endl; //輸出 hello world!
return 0;
}
五、字符串的遍歷
可以使用迭代器、下標運算符等方式遍歷字符串中的每一個字符。例如:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str1 = "hello world!";
for(int i = 0; i < str1.size(); i++)
cout << str1[i] << endl;
cout << "---------------------" << endl;
for(auto it = str1.begin(); it != str1.end(); it++)
cout << *it << endl;
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/246498.html
微信掃一掃
支付寶掃一掃