如何将字符串拆分为一组 3 个字符,它们之间有空格

How to split a string into groups of 3 characters with space between them

本文关键字:字符 空格 之间 一组 字符串 拆分      更新时间:2023-10-16

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