c++中一个string类型的字符串例如“205 只能 5 5”如何找第三个和第四个空格的位置,
时间: 2024-02-28 11:57:39 浏览: 14
可以使用循环和`find()`函数来找到第三个和第四个空格的位置。具体来说,可以循环两次,每次使用`find()`函数查找下一个空格的位置,并将查找的起始位置设置为上一个空格的位置加一。代码示例如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "205 只能 5 5";
int count = 0; // 记录空格的数量
int pos = -1; // 查找空格的起始位置
while (count < 4)
{
pos = str.find(" ", pos+1); // 从上一个空格的位置加1开始查找下一个空格的位置
if (pos == string::npos) // 如果没找到则退出循环
{
break;
}
count++; // 找到了一个空格,数量加1
}
if (count == 4) // 如果找到了第四个空格
{
cout << "第三个空格的位置:" << str.find(" ", str.find(" ", str.find(" ")+1)+1) << endl;
cout << "第四个空格的位置:" << pos << endl;
}
else
{
cout << "字符串中没有第三个和第四个空格!" << endl;
}
return 0;
}
```
输出结果为:
```
第三个空格的位置:9
第四个空格的位置:12
```
这里使用了循环和`find()`函数来查找第三个和第四个空格的位置。每次查找下一个空格的位置时,需要从上一个空格的位置加一开始查找。如果找到了第四个空格,则输出其位置。注意,如果字符串中没有第三个和第四个空格,则需要特殊处理。