C++ - 查找函数无法在子字符串上执行

C++ - find function does not work executed on substring

本文关键字:字符串 执行 查找 函数 C++      更新时间:2023-10-16

我确实遇到了一个算法问题,我想用它来将命令行拆分为几个子字符串。 例如,字符串"Hello World -n filename"应该切成"Hello""World""-n filename"

这是我的整个代码示例:

string hello = "Hello World -n filename";
uint64_t startIndex = 0;
uint64_t endIndex = hello.length() - 1;
while(startIndex < endIndex) {
uint64_t nextWhiteSpaceIndex;
string value;
if(hello.at(startIndex) != '-') {
nextWhiteSpaceIndex = hello.substr(startIndex).find(" ");
value = hello.substr(startIndex, nextWhiteSpaceIndex);
cout << value << endl;
} else {
nextWhiteSpaceIndex = hello.substr(hello.substr(startIndex).find(" ")).find(" ");
value = hello.substr(startIndex, nextWhiteSpaceIndex);
cout << value << endl;
}
startIndex = nextWhiteSpaceIndex + 1;
}

而且我确实对此命令有问题:

nextWhiteSpaceIndex = hello.substr(startIndex).find(" ");

这被放置在 while 循环中,看起来

...
.substr(startIndex)

。部分被完全忽略。第一次循环运行工作正常,但在第二次/之后的下一次循环中,下一个 WhiteSpaceIndex 没有分配正确的下一个索引。它总是打印"Hello" "World" "World" "World" "World"并继续打印"World"

你们有提示吗,为什么这不起作用?在通过网络进行研究期间,我找不到合适的解释。

hello永远不会改变,但你只在它的一部分(substr(上使用find,然后一遍又一遍地对整个字符串(hello(调用substr(startIndex)

  1. "Hello World -n filename".find(" ")-> 5
  2. "World -n filename".find(" ")-> 5 再次("世界"与"你好"长度相同(
  3. "World -n filename".find(" ")-> 5

您可以使用std::string::find的第二个参数(size_type pos(来指定开始搜索的起始偏移量,并创建更少的临时字符串:

#include <iostream>
using namespace std;
int main() {
const string hello = "Hello World -n filename";
size_t startIndex = 0, pos = 0;
bool eat = true;
while(true) {
pos = hello.find('x20', pos);
if(pos == string::npos) {
cout << hello.substr(startIndex) << endl;
break;
}
else if(eat && hello[startIndex] == '-') {
eat = false;
++pos;
continue;
}
cout << hello.substr(startIndex, pos - startIndex) << endl;
startIndex = ++pos;
eat = true;
}
return 0;
}

输出:

$ c++ main.cpp && ./a.out
Hello
World
-n filename

你不能做这样的事情吗

#include <sstream>
#include <stdio>
#include <vector>
using namespace std;
int main ()
{
string hello = "Hello World -n filename";
stringstream ss (hello);
vector<string> v;
string s, t;
while (ss >> s)
{
if (s[0] == '-')
{   
ss >> t;
v.push_back (s + " " + t); 
}   
else
v.push_back (s);
}
for (auto i : v)
clog << i << endl;
return 0;
}

生产

$ ./a.out
Hello
World
-n filename

如果输出nextWhiteSpaceIndex的值,您将始终看到:5、5、5、5...它是相对于startIndex的索引,因此只需将最后一行更改为startIndex += nextWhiteSpaceIndex + 1;可能会快速解决问题。

(你不是拿了太多子字符串吗?std::string::find可以将搜索开始索引作为参数,因此您可以在始终相同的缓冲区上执行整个搜索。