string的好处是:
文章目录
当谈到使用 C++ 中的 string 类型时,我们可以看到它具有许多方便的特性。
① 可以直接赋值:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello"; // 直接赋值
std::string str2;
str2 = "World"; // 直接赋值
std::cout << str1 + " " + str2 << std::endl; // 输出:Hello World
return 0;
}
② 可以直接加:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + " " + str2; // 直接加
std::cout << result << std::endl; // 输出:Hello World
return 0;
}
③ 可以直接比较:
#include <iostream>
#include <string>
int main() {
std::string str1 = "abc";
std::string str2 = "def";
if (str1 == str2) { // 直接比较
std::cout << "Strings are equal" << std::endl;
} else {
std::cout << "Strings are not equal" << std::endl;
}
return 0;
}
④ 可以对 string 数组直接 sort:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string arr[] = {"apple", "orange", "banana"};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n); // 对string数组直接sort
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl; // 输出:apple banana orange
return 0;
}
⑤ 动态空间,比如说题目说 1e5 个字符串,每个字符串长度不超过 1e5,所有字符串长度之和不超过 1e6,那么不可能创建 char 二维数组,只能用 string 数组:
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> strArray(100000); // 创建一个包含 100000 个字符串的动态数组
strArray[0] = "Hello";
strArray[1] = "World";
std::cout << strArray[0] + " " + strArray[1] << std::endl; // 输出:Hello World
return 0;
}
⑥ 可以直接用 reverse 函数翻转,在某些水题挺方便的:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "hello";
std::reverse(str.begin(), str.end()); // 使用 reverse 函数翻转
std::cout << str << std::endl; // 输出:olleh
return 0;
}