一、常用的字符串處理方式
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-hant/n/286844.html