如何将一个以零开头的整数插入std :: string? [英] How to insert an integer with leading zeros into a std::string?
问题描述
在C ++ 14程序中,为我提供了一个字符串,例如
In a C++14 program, I am given a string like
std::string s = "MyFile####.mp4";
以及0到几百之间的整数。 (永远不会超过一千,但要以防万一,请输入四位数。)我想用整数值替换 ####
,并用前导所需的零,以匹配'#'
字符的数量。修改s或产生这样的新字符串的巧妙的C ++ 11/14方法是什么?
and an integer 0 to a few hundred. (It'll never be a thousand or more, but four digits just in case.) I want to replace the "####
" with the integer value, with leading zeros as needed to match the number of '#'
characters. What is the slick C++11/14 way to modify s or produce a new string like that?
通常我会使用 char *
字符串和 snprintf()
, strchr()
来找到 #
,但我应该理解现代并使用 std :: string
较多,但只知道最简单的用法。
Normally I would use char*
strings and snprintf()
, strchr()
to find the "#
", but figure I should get with modern times and use std::string
more often, but know only the simplest uses of it.
推荐答案
用C ++ 11/14修改s或生成这样的新字符串的方法是什么?
What is the slick C++11/14 way to modify s or produce a new string like that?
我不知道它是否足够光滑,但我建议使用 std :: transform()
,lambda函数和反向迭代器。
I don't know if it's slick enough but I propose the use of std::transform()
, a lambda function and reverse iterators.
类似
#include <string>
#include <iostream>
#include <algorithm>
int main ()
{
std::string str { "MyFile####.mp4" };
int num { 742 };
std::transform(str.rbegin(), str.rend(), str.rbegin(),
[&](auto ch)
{
if ( '#' == ch )
{
ch = "0123456789"[num % 10]; // or '0' + num % 10;
num /= 10;
}
return ch;
} // end of lambda function passed in as a parameter
); // end of std::transform()
std::cout << str << std::endl; // print MyFile0742.mp4
}
这篇关于如何将一个以零开头的整数插入std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!