std::string 字符串裁减
时间: 2024-04-01 21:29:24 浏览: 12
std::string是C++标准库中的一个类,用于处理字符串。它提供了一系列的成员函数和操作符,可以方便地对字符串进行操作和处理。
要对std::string进行裁减,可以使用substr()函数。substr()函数接受两个参数,第一个参数是起始位置的索引,第二个参数是要裁减的字符数。它会返回一个新的std::string对象,包含从起始位置开始的指定字符数的子串。
下面是一个示例代码,展示了如何使用substr()函数进行字符串裁减:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string subStr = str.substr(7, 5); // 从索引7开始,裁减5个字符
std::cout << subStr << std::endl; // 输出 "World"
return 0;
}
```
在上面的代码中,我们定义了一个std::string对象str,并初始化为"Hello, World!"。然后使用substr()函数从索引7开始,裁减5个字符,得到子串"World"。最后将子串输出到控制台。
相关问题
std::string 比较字符串
std::string是C++标准库中的一个类,用于表示和操作字符串。在std::string类中,可以使用比较运算符(如==、!=、<、>、<=、>=)来比较字符串的大小。
比较字符串时,会按照字典序进行比较。具体比较规则如下:
- 如果两个字符串的长度不同,那么较短的字符串会被认为是较小的。
- 如果两个字符串的长度相同,那么会逐个比较对应位置上的字符,直到找到不同的字符为止。根据不同字符的ASCII码值来确定大小关系。
下面是一个示例代码,演示了如何使用std::string进行字符串比较:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
if (str1 == str2) {
std::cout << "str1和str2相等" << std::endl;
} else if (str1 < str2) {
std::cout << "str1小于str2" << std::endl;
} else {
std::cout << "str1大于str2" << std::endl;
}
return 0;
}
```
输出结果为:"str1小于str2",因为按照字典序,"hello"小于"world"。
std::string 分割字符串
可以使用 stringstream 和 getline 函数来分割字符串,具体实现如下:
```c++
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::stringstream ss(s);
std::string token;
while (std::getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string s = "hello world";
std::vector<std::string> tokens = split(s, ' ');
for (const auto& token : tokens) {
std::cout << token << std::endl;
}
return 0;
}
```
输出结果为:
```
hello
world
```