一、常用的字元串處理方式
C++中的字元串是由字元組成的數組,每個字元都有一個對應的ASCII代碼值,在處理字元串時,我們常用的方式 mainly 有:
1、數組下標訪問:通過下標操作符[]獲取字元串中的某個字元,可以直接對字元進行修改。例如:
string str = "hello world";
for (int i = 0; i < str.size(); i++) {
cout << str[i] << " ";
}
2、指針遍歷:利用指針逐個訪問字元串中的字元,注意需要判斷字元串的結束符’\0’,以免指針越界,例如:
char str[] = "hello world";
char *ptr = str;
while (*ptr != '\0') {
cout << *ptr << " ";
ptr++;
}
3、字元串迭代器:使用迭代器來訪問字元串中的元素,具有安全性能好、代碼讀寫方便的優點。例如:
string str = "hello world";
for (auto it = str.begin(); it != str.end(); it++) {
cout << *it << " ";
}
二、常用的字元串處理函數
字元串處理函數包括一些可以對字元串進行查找、替換、刪除等操作的函數。常用的字元串處理函數 mainly 有:
1、查找函數find:查找字元串中第一個出現的子串位置,如果找不到則返回-1。例如:
string str = "hello world";
int pos = str.find("world");
if (pos != -1) {
cout << "找到了!位置是:" << pos << endl;
}
else {
cout << "未找到!" << endl;
}
2、替換函數replace:將字元串中的部分子串替換成指定的新串。例如:
string str = "hello world";
str.replace(6, 5, "China");
cout << str << endl;
3、插入函數insert:將指定字元串插入到目標字元串中的指定位置。例如:
string str = "hello world";
str.insert(6, "China ");
cout << str << endl;
4、截取函數substr:從指定位置開始,截取指定長度的子串。例如:
string str = "hello world";
string newStr = str.substr(6, 5);
cout << newStr << endl;
5、刪除函數erase:刪除字元串中的一段子串。例如:
string str = "hello world";
str.erase(6, 5);
cout << str << endl;
三、字元串幾個常用的處理函數
主要介紹幾個特殊的字元串處理函數,包括大小寫轉換、去掉字元串中的空格、特殊字元處理等。
1、大小寫轉換函數:可以將字元串中的所有字元轉換為大寫或小寫形式,分別對應toupper和tolower函數。例如:
string str = "Hello World";
transform(str.begin(), str.end(), str.begin(), ::tolower); // 轉換為小寫字元
cout << str << endl;
2、去空格函數:可以將字元串兩端的空格去除,注意該函數只能去掉兩端的空格,不能去掉中間的空格。例如:
string str = " hello world ";
int left = str.find_first_not_of(" "); // 查找左側第一個非空字元
int right = str.find_last_not_of(" "); // 查找右側第一個非空字元
str = str.substr(left, right - left + 1); // 截取子字元串
cout << str << endl;
3、特殊字元處理函數:可以將字元串中出現的特殊字元轉義成其他字元,例如C++中規定雙引號”需要用\”來表示,單引號’需要用\’來表示。例如:
string str = "I said \"Hello World!\"";
string newStr;
for (int i = 0; i < str.size(); i++) {
if (str[i] == '"') {
newStr += "\\\"";
}
else {
newStr += str[i];
}
}
cout << newStr << endl;
四、string處理字元串常用的方法
string是C++中常用的字元串類型,其常用的處理方法 mainly 有:
1、獲取字元串長度size函數:獲取當前字元串的長度,注意字元串長度不包括結束符’\0’。例如:
string str = "hello world";
cout << str.size() << endl;
2、比較字元串大小compare函數:比較兩個字元串的大小,返回值為0表示兩個字元串相等,為正數表示第一個字元串大於第二個字元串,為負數表示第一個字元串小於第二個字元串。例如:
string str1 = "hello";
string str2 = "world";
int res = str1.compare(str2);
if (res == 0) {
cout << "兩個字元串相等" < 0) {
cout << "str1大於str2" << endl;
}
else {
cout << "str1小於str2" << endl;
}
3、清空字元串clear函數:清空當前字元串內容,讓當前字元串變為空字元串。例如:
string str = "hello world";
str.clear();
cout << str << endl;
4、字元串連接操作+運算符:將兩個字元串連接成一個新的字元串。例如:
string str1 = "hello";
string str2 = "world";
string str3 = str1 + " " + str2;
cout << str3 << endl;
5、字元串複製操作=運算符:將一個字元串複製到另一個字元串中。例如:
string str1 = "hello world";
string str2 = str1;
cout << str2 << endl;
總結
本文主要講解了C++中字元串處理的常用函數,從字元串處理方式、常用函數、特殊字元處理、string類型的方法等四個方面進行了詳細的介紹。在實際的編程過程中,了解這些常用的字元串處理方法,可以使得編程更加高效、方便。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/286844.html