如果字符串中没有空格,如何解析带有数字和字符的字符串并分隔数字和字符
How do you parse a string with numbers and chars and separate the numbers and chars if there is no spaces in the string?
我有一个字符串
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;
}
链接到演示
相关文章:
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何检查一个c++字符串中有多少相同的字符/数字
- 当我输入字符类型的数字时,为什么我无法获得整数?
- scanf() 只取数字作为输入,避免使用其他字符
- 递归形成字符串中所有数字字符的中间和?
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 如何在 getline 中删除/忽略超过特定数字的字符?
- C++输出奇怪的字符而不是数字 (Windows)
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 如何在C++中有效地将数字值重新分配给字符数组
- 我应该以字符形式存储数字以节省内存吗?
- C++ 从 std::string 中删除所有非数字字符
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 不反转数字的字符反转
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如果是数字或字符,请检查输入
- 如何将字符更改为数字?
- 生成随机字符/数字
- 如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格
- 字符数字 ['0'.."9'] 需要具有连续的数值吗?