J D*_*ope 1 c++ arrays string char
我对编码真的很陌生,并且在尝试在 C++ 中拆分字符串时遇到了一些麻烦。我想知道如何拆分字符串,该字符串const char names[] (i.e. "Mary, Jan, Jane")在 C++ 中作为 a 输入,而不使用任何外部库(即我不想使用#include <string>等 - 尽管我可以使用#include <cstring>)。
我尝试过使用:
const char names[] = "Mary, Jan, Jane";
char *token = strtok(names, ",");
while (token != NULL) {
token = strtok(NULL, " ");
}
Run Code Online (Sandbox Code Playgroud)
但我似乎无法传递一个 const 字符数组,我还想知道如何访问所有单独的“令牌”?
另外,我尝试将输入更改为 just char names[](但我确实需要输入为常量),并且出现分段错误,我不明白为什么。
使用std::string而不是 char 数组并利用std::stringstream类。将,分隔符传递给std::getline函数:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string names = "Mary, Jan, Jane";
std::string temp;
std::istringstream ss(names);
while (std::getline(ss, temp, ',')) {
std::cout << temp << '\n';
}
}
Run Code Online (Sandbox Code Playgroud)
剩下的唯一事情就是处理每个字符串中的前导空格字符:
if (temp.front() == ' ') {
temp.erase(0, 1);
}
Run Code Online (Sandbox Code Playgroud)