c++ - C++ - 在子字符串上执行的查找函数不起作用
问题描述
我确实遇到了一个算法问题,我想用它来将命令行拆分为几个子字符串。例如,字符串"Hello World -n filename"
应该被分割成"Hello"
"World"
and "-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)
...部分被完全忽略。第一个循环运行正常,但在第二个/以下 nextWhiteSpaceIndex 没有得到正确的下一个索引分配。它总是打印"Hello" "World" "World" "World" "World"
并继续打印"World"
。
你们有提示吗,为什么这不起作用?在通过网络进行研究期间,我找不到合适的解释。
解决方案
你不能做类似的事情吗
#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
推荐阅读
- azure - 为什么我的 k8s Nginx 入口控制器提供两个证书(其中一个是 Kubernetes 假证书)?
- azure-devops-server - 在 Azure Devops 服务器中根据用户故事或任务筛选创建查询
- kotlin - 找不到片段构造函数kotlin
- python - 我无法使用 Selenium Python 在亚马逊上单击“立即购买”按钮
- pine-script - 修复松树筛选器转换
- android - Firebase 实时数据库数据自动被删除
- kubernetes - Argo 提前停止工作流程,标记完成
- encoding - 编码错误:用越南语从头开始训练 BERT
- .net-core - 信号器:身份验证后,我在客户端收到错误 400(错误请求)
- flutter - 没有为“Registrar”类型定义方法“registerMessageHandler”