如何将字符串拆分为一组 3 个字符,它们之间有空格
How to split a string into groups of 3 characters with space between them
i 有字符串
std::string MegaNum( float 10020030040 )
重要的是转换我的字符串,以便我们可以为每 3 位数字放置一个空格。我们将如何对它们进行分组并不那么重要。
我想转换为 4 位数字值为 1-3 位的新值
float 1; /*with value 10*/
float 2; /*with value 020*/
float 3; /*with value 030*/
float 4; /*with value 040*/
然后将其打印为
10 020 030 040
转换我的字符串,以便我们可以为每 3 位数字放置一个空格。
由于您是从字符串开始的,因此您可以考虑直接执行操作(没有浮点数数学)。
以下函数获取一个字符串,并从最不重要的字符(最右边)中计算出 3 位数字,并返回插入空格的数字(行增长)。 (它不确认数字的有效性,不检查字符是否为数字)
std::string digiSpace3(std::string s)
{ // sSize must be signed int of sufficient size
int32_t sSize = static_cast<int32_t>(s.size());
if (sSize > 3)
for (int32_t indx = (sSize - 3); indx > 0; indx -= 3)
s.insert(static_cast<size_t>(indx), 1, ' ');
return(s);
}
像这样使用:
std::string MegaNum = "10020030040" ;
// std::string MegaNum ( std::to_string(10020030040) ) ; //also works
std::cout << "n " << digiSpace3(MegaNum) << std::endl;
并生产
10 020 030 040
仅供参考 - 我的编译器不接受
std::string MegaNum( float 10020030040 );
和报告
error: expected ‘,’ or ‘...’ before numeric constant
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 防止在字符数组中输入双倍空格在 C++
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- 将空格作为单字符数据类型的输入?
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- iStream 运算符跳过空格字符
- 从字符数组中删除双空格
- 循环以从字符数组中删除过多的空格 (C++)
- 在字符名称 c++ 中留出空格
- 检查字符串中的小写字符或空格.布尔值不起作用
- CIN 双精度和不带空格的字符串会导致错误
- 在 C++ 中输入带有空格的字符数组
- 如何将字符串拆分为一组 3 个字符,它们之间有空格
- 在字符串中的字符前添加空格C++插入函数
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- QString 从行首或行尾修剪非空格字符
- 回文,不包括特殊字符和空格
- 将字符串分为连续的非空格字符的序列