c – 如何将带前导零的整数插入到std :: string中?

在C 14程序中,我给了一个字符串
std::string  s = "MyFile####.mp4";

和0到几百的整数. (它永远不会是一千个或更多,但只有四个数字以防万一.)我想用整数值替换“####”,并根据需要使用前导零来匹配“#”字符的数量.什么是光滑的C 11/14修改s或生成这样的新字符串的方法?

通常我会使用char * strings和snprintf(),strchr()来查找“#”,但是我应该使用现代时间并更频繁地使用std :: string,但只知道它的最简单用法.

解决方法

What is the slick C++11/14 way to modify s or produce a new string like that?

我不知道它是否足够光滑,但我建议使用std :: transform(),一个lambda函数和反向迭代器.

就像是

#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
 }

相关文章

首先GDB是类unix系统下一个优秀的调试工具, 当然作为debug代...
1. C语言定义1个数组的时候, 必须同时指定它的长度.例如:int...
C++的auto关键字在C+⬑新标准出来之前基本...
const关键字是用于定义一个不该被改变的对象,它的作用是告诉...
文章浏览阅读315次。之前用C语言编过链表,这几天突然想用C+...
文章浏览阅读219次。碰到问题就要记录下来,防止遗忘吧。文章...