博主將從C++標準庫中的
std::string
出發,詳細探討字符串的處理方法,涵蓋常見操作、性能優化和實際應用場景。以下內容將圍繞std::string
的使用展開,結合代碼示例進行說明。
一、std::string
的基本操作
1.1 創建與初始化
std::string
提供了多種構造函數,支持從C風格字符串、字符數組、字符列表等初始化。
示例:
#include <iostream>
#include <string>int main() {// 默認構造函數std::string s1;// 從C風格字符串初始化std::string s2 = "Hello, World!";// 從字符數組初始化char arr[] = {'H', 'i', '\0'};std::string s3(arr);// 重復字符初始化std::string s4(5, 'A'); // "AAAAA"std::cout << "s2: " << s2 << std::endl;std::cout << "s4: " << s4 << std::endl;return 0;
}
輸出:
s2: Hello, World!
s4: AAAAA
1.2 字符串的訪問與修改
std::string
提供了多種訪問和修改字符串內容的方法。
示例:
#include <iostream>
#include <string>int main() {std::string s = "Hello";// 訪問字符char c = s[0]; // 'H'char c2 = s.at(1); // 'e'// 修改字符s[0] = 'h'; // "hello"s.at(1) = 'E'; // "hEllo"// 添加字符s += ", World!"; // "hEllo, World!"// 插入字符s.insert(5, " C++"); // "hEllo C++, World!"// 刪除字符s.erase(5, 4); // "hEllo, World!"std::cout << s << std::endl;return 0;
}
輸出:
hEllo, World!
1.3 字符串的比較
std::string
支持通過 ==
、!=
、<
、>
等運算符進行比較。
示例:
#include <iostream>
#include <string>int main() {std::string s1 = "apple";std::string s2 = "banana";if (s1 == s2) {std::cout << "s1 and s2 are equal" << std::endl;} else if (s1 < s2) {std::cout << "s1 is less than s2" << std::endl;} else {std::cout << "s1 is greater than s2" << std::endl;}return 0;
}
輸出:
s1 is less than s2
二、字符串的查找與替換
2.1 查找子字符串
std::string
提供了 find()
和 rfind()
方法,分別用于查找子字符串的首次和最后一次出現位置。
示例:
#include <iostream>
#include <string>int main() {std::string s = "Hello, World! Hello, C++!";// 查找子字符串size_t pos = s.find("Hello");if (pos != std::string::npos) {std::cout << "Found 'Hello' at position: " << pos << std::endl;}// 從后向前查找size_t rpos = s.rfind("Hello");if (rpos != std::string::npos) {std::cout << "Last 'Hello' found at position: " << rpos << std::endl;}return 0;
}
輸出:
Found 'Hello' at position: 0
Last 'Hello' found at position: 14
2.2 替換子字符串
std::string
提供了 replace()
方法,用于替換指定位置的子字符串。
示例:
#include <iostream>
#include <string>int main() {std::string s = "Hello, World!";// 替換子字符串s.replace(7, 5, "C++"); // "Hello, C++!"std::cout << s << std::endl;return 0;
}
輸出:
Hello, C++!
三、字符串的分割與連接
3.1 分割字符串
C++標準庫沒有直接提供字符串分割函數,但可以通過 find()
和 substr()
實現。
示例:
#include <iostream>
#include <string>
#include <vector>std::vector<std::string> split(const std::string& s, char delimiter) {std::vector<std::string> tokens;size_t start = 0;size_t end = s.find(delimiter);while (end != std::string::npos) {tokens.push_back(s.substr(start, end - start));start = end + 1;end = s.find(delimiter, start);}tokens.push_back(s.substr(start));return tokens;
}int main() {std::string s = "apple,banana,orange";std::vector<std::string> fruits = split(s, ',');for (const auto& fruit : fruits) {std::cout << fruit << std::endl;}return 0;
}
輸出:
apple
banana
orange
3.2 連接字符串
std::string
支持通過 +
或 append()
方法連接字符串。
示例:
#include <iostream>
#include <string>int main() {std::string s1 = "Hello";std::string s2 = "World";// 使用 + 連接std::string s3 = s1 + ", " + s2 + "!";// 使用 append() 連接s1.append(", ").append(s2).append("!");std::cout << s3 << std::endl;std::cout << s1 << std::endl;return 0;
}
輸出:
Hello, World!
Hello, World!
四、字符串的性能優化
4.1 預分配內存
通過 reserve()
方法預分配內存,減少頻繁擴容的開銷。
示例:
#include <iostream>
#include <string>int main() {std::string s;s.reserve(100); // 預分配100字節內存for (int i = 0; i < 100; ++i) {s += 'a';}std::cout << "Length: " << s.length() << std::endl;std::cout << "Capacity: " << s.capacity() << std::endl;return 0;
}
輸出:
Length: 100
Capacity: 100
4.2 使用 std::string_view
(C++17)
std::string_view
提供零拷貝的字符串訪問,適合只讀操作。
示例:
#include <iostream>
#include <string>
#include <string_view>void print(std::string_view sv) {std::cout << sv << std::endl;
}int main() {std::string s = "Hello, World!";print(s); // 無需拷貝print("Literal"); // 直接處理字面量return 0;
}
輸出:
Hello, World!
Literal
五、實際應用場景
5.1 配置文件解析
使用字符串分割和查找功能解析配置文件。
示例:
# config.ini
name=John
age=30
#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>std::unordered_map<std::string, std::string> parse_config(const std::string& filename) {std::unordered_map<std::string, std::string> config;std::ifstream file(filename);std::string line;while (std::getline(file, line)) {size_t pos = line.find('=');if (pos != std::string::npos) {std::string key = line.substr(0, pos);std::string value = line.substr(pos + 1);config[key] = value;}}return config;
}int main() {auto config = parse_config("config.ini");std::cout << "Name: " << config["name"] << std::endl;std::cout << "Age: " << config["age"] << std::endl;return 0;
}
輸出:
Name: John
Age: 30
六、總結
std::string
是C++中處理字符串的核心工具,提供了豐富的操作方法。通過合理使用這些方法,可以高效地完成字符串的創建、修改、查找、分割和連接等任務。在實際開發中,結合性能優化技巧(如預分配內存、使用 std::string_view
),可以進一步提升程序的效率。