在 c 中解析逗号分隔的字符串序列-ag捕鱼王app官网

在 c 中解析逗号分隔的字符串序列

作者:迹忆客 最近更新:2023/04/08 浏览次数:

本文将介绍有关如何在 c 中解析逗号分隔的字符串序列的多种方法。


使用 std::string::findstd::string::erase 函数来解析 c 中逗号分隔的字符串序列

std::find 方法是 std::string 类的内置函数,可用于查找给定子字符串的位置。在这种情况下,它采用一个参数来表示要找到的子字符串。任何多字符字符串变量都可以初始化为作为参数传递。尽管在下面的示例中,我们声明了一个包含字符串的逗号。由于 find 方法会返回子字符串和 string::npos 的位置(当未找到子字符串时),因此我们可以将比较表达式放入 while 循环中,该循环将执行直到表达式计算为真为止。

我们还将每次迭代后解析的字符串存储在 vector 容器中。然后,调用 erase 方法以删除在第一个逗号分隔符之前和包括的字符,以便在下一次迭代中继续处理相同的 string 对象。最后,我们将存储在向量中的元素输出到 cout 流。

#include #include #include #include #include using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector;
using std::stringstream;
int main(){
    string text = "1,2,3,4,5,6,7,8,9,10";
    string delimiter = ",";
    vector<string> words{};
    size_t pos = 0;
    while ((pos = text.find(delimiter)) != string::npos) {
        words.push_back(text.substr(0, pos));
        text.erase(0, pos  delimiter.length());
    }
    for (const auto &str : words) {
        cout << str << endl;
    }
    return exit_success;
}

输出:

1
2
3
4
5
6
7
8
9

使用 std::getline 函数来解析逗号分隔的字符串序列

先前的ag捕鱼王app官网的解决方案未提取逗号分隔序列中的最后一个数字。因此,最好是通过 std::getline 函数使用以下方法,而不是在前面的代码示例中添加条件检查。getline 从给定的输入流中读取字符,并将其存储到 string 对象中。该函数还使用可选的第三个参数来指定分隔输入字符串的定界符。在每次迭代时,我们还将提取的字符串存储在 std::vector 容器中,以备后用。

#include #include #include #include #include using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector;
using std::stringstream;
int main(){
    string text = "1,2,3,4,5,6,7,8,9,10";
    char delimiter = ',';
    vector<string> words{};
    stringstream sstream(text);
    string word;
    while (std::getline(sstream, word, delimiter)){
        words.push_back(word);
    }
    for (const auto &str : words) {
        cout << str << endl;
    }
    return exit_success;
}

输出:

1
2
3
4
5
6
7
8
9
10

上一篇:

下一篇:在 c 中删除字符串中的空格

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

arduino 中停止循环

发布时间:2024/03/13 浏览次数:444 分类:c

可以使用 exit(0),无限循环和 sleep_n0m1 库在 arduino 中停止循环。

arduino 复位

发布时间:2024/03/13 浏览次数:315 分类:c

可以通过使用复位按钮,softwarereset 库和 adafruit sleepydog 库来复位 arduino。

发布时间:2024/03/13 浏览次数:181 分类:c

可以使用简单的方法 toint()函数和 serial.parseint()函数将 char 转换为 int。

arduino 串口打印多个变量

发布时间:2024/03/13 浏览次数:381 分类:c

可以使用 serial.print()和 serial.println()函数在串口监视器上显示变量值。

arduino if 语句

发布时间:2024/03/13 浏览次数:123 分类:c

可以使用 if 语句检查 arduino 中的不同条件。

arduino icsp

发布时间:2024/03/13 浏览次数:214 分类:c

icsp 引脚用于两个 arduino 之间的通信以及对 arduino 引导加载程序进行编程。

发布时间:2024/03/13 浏览次数:151 分类:c

可以使用 arduino 中的循环制作计数器。

使用 c 编程 arduino

发布时间:2024/03/13 浏览次数:127 分类:c

本教程将讨论使用 arduino ide 在 c 中对 arduino 进行编程。

arduino 中的子程序

发布时间:2024/03/13 浏览次数:168 分类:c

可以通过在 arduino 中声明函数来处理子程序。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图