如果字符串中没有空格,如何解析带有数字和字符的字符串并分隔数字和字符

How do you parse a string with numbers and chars and separate the numbers and chars if there is no spaces in the string?

本文关键字:字符 数字 字符串 分隔 串并 空格 如果 何解析      更新时间:2023-10-16

我有一个字符串

123test

如何分离 123 并测试和存储在两个变量中?

例如,使用 sscanf:

char str[] = "123test";
char str2[10];
int i;
sscanf(str, "%d%s", &i, str2);

使用 C++ 提供的工具:字符串和流。

#include <iostream>
#include <string>
#include <sstream>
int main()
{
    int num;
    std::string str;
    std::istringstream ss{"123test"};
    ss >> num >> str;
    std::cout << "num = " << num << std::endl;
    std::cout << "str = " << str << std::endl;
    return 0;
}

链接到演示