将数字打印为字符串类型的数字
Print number as number in string type
我有以下代码:
string a = "wwwwaaadexxxxxx";
预期输出:"w4a3d1e1x6";
我的代码中有int count = 1; ... count++;
另外,在我的代码的某个地方,我必须将此计数打印为a[i]
,但仅作为数字…比如1、2、3,而不是1、2、3的等效字符。
我正在尝试以下内容:printf("%c%d",a[i],count);
我也读到像这样的东西:
stringstream ss;
ss << 100
在CPP中正确的方法是什么?
编辑:
so i修改代码,在字符串的索引i处添加一个数字:
stringstream newSS;
newSS << count;
char t = newSS.str().at(0);
a[i] = t;
您可以使用stringstream将字符串和计数连接起来,
stringstream newSS;
newSS << a[i] << count;
,然后最后将其转换为字符串,然后打印或返回(如果在函数中完成)
string output = newSS.str();
cout << output << endl;
但是如果您的目标只是打印输出,那么使用printf
就可以了。
如果需要就地更新,则可以使用两个指针。让它们是i,j。
您使用j来设置新值,使用i来计算计数。这是标准的runLength编码问题
没有"正确"的方法。你可以使用snprintf, stringstream等。或者你可以滚动你的算法。假设这是一个以10为基数的数,您需要以10为基数的数。
#include <iostream>
#include <string>
#include <algorithm>
int main(void)
{
int a = 1194;
int rem = 0;
std::string output;
do {
rem = a % 10;
a = a / 10;
output.append(1, rem + '0');
} while(a != 0);
std::reverse(output.begin(), output.end());
std::cout << output << std::endl;
return 0;
}
相关文章:
- 你能在 c++ 中将不同的数字类型加在一起吗?
- 检测<T>某些非数字类型 T 的 std::numeric::type 的特化
- 为什么数字类型只有"to_string()"?
- 从 std::stringstream 读取uint8_t为数字类型
- 枚举超过了最大数字类型的大小
- 为什么将指针铸成数字类型是不安全的
- 我应该始终将适当的文字用于数字类型
- 如何识别C中字符串中包含的数字类型
- 如何对具有带符号数字类型的事物进行谓词
- 我可以得到一个适用于任何数字类型的模板化均匀分布生成器吗?
- C++隐式数字类型降级
- 依靠任何数字类型(无符号、整数等)的隐式提升来加倍是否安全
- 用于显示不同数字类型的函数重载
- 创建几个相互不兼容的数字类型
- 同类数字类型之间的转换
- 数字类型介于0和1之间
- 将字符串转换为数字类型的通用方法
- 为小循环计数器选择什么数字类型
- 如何将处理不同数字类型的C函数库包装到c++模板类中
- 如何将来自用户定义文字的可变char模板参数转换回数字类型