C++ - 查找函数无法在子字符串上执行
C++ - find function does not work executed on substring
我确实遇到了一个算法问题,我想用它来将命令行拆分为几个子字符串。 例如,字符串"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)
。
"Hello World -n filename".find(" ")
-> 5"World -n filename".find(" ")
-> 5 再次("世界"与"你好"长度相同("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
可以将搜索开始索引作为参数,因此您可以在始终相同的缓冲区上执行整个搜索。
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 如何执行不区分大小写的字符串比较?
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- readAll() 或 readAllStandardOutput() 在执行之前也返回一个空字符串
- 如何在没有外部库的情况下使用C++03约束执行基于正则表达式的字符串操作
- 如何在C++中对静态缓冲区执行字符串格式化?
- C++ - 查找函数无法在子字符串上执行
- 如何在 Python 或 C++ 中执行任意字符串?
- 是否有用于执行反向字符串拆分器的开箱即用功能?
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- 如何对字符串作为指针执行大写转换
- 代码问题将字符串转换为图表执行
- QProcess::执行环境变量扩展字符串
- 如何使用 Win32 WCHAR 执行字符串操作
- 如何对 n 个字符串执行操作,然后在C++中打印它们
- 如何对字符串执行路径操作
- 如何对具有十六进制值的字符串执行按字节 XOR,以 C++ 为单位
- 如果可能,尝试对字符串执行静态断言,或者在不是时回退到运行时检查
- 试图对字符串执行索引搜索