c++中如何以一个字符’i’为准把string字符串中’i’两边的字符分成两个子字符串

在C++中,可以使用字符串处理函数和下标操作来以一个字符’i’为准把std::string字符串中’i’两边的字符分成两个子字符串。下面是一个示例代码:

#include
#include

int main() {
std::string str = “Hello World”;
char pivot = ‘i’;
size_t pos = str.find(pivot); // 在字符串中查找字符’i’的位置
if (pos == std::string::npos) {
std::cout << “没有找到字符’i’” << std::endl;
return 0;
}

std::string subStr1 = str.substr(0, pos); // 获取’i’之前的子字符串
std::string subStr2 = str.substr(pos + 1); // 获取’i’之后的子字符串

std::cout << “子字符串1:” << subStr1 << std::endl;
std::cout << “子字符串2:” << subStr2 << std::endl;

return 0;

}

首先,使用find函数在字符串中查找字符’i’的位置,如果找到则返回位置索引,否则返回std::string::npos。

然后,利用substr函数分别获取从字符串开始位置到’i’位置之间的子字符串subStr1,以及从’i’位置之后到字符串末尾的子字符串subStr2。

最后,打印输出子字符串。

以上代码输出结果为:

子字符串1:Hello W
子字符串2:orld

猜你喜欢

转载自blog.csdn.net/weixin_43466192/article/details/131604556