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

How to insert an integer with leading zeros into a std::string?

本文关键字:插入 整数 std string      更新时间:2023-10-16

在 C++14 程序中,我得到了一个类似

std::string  s = "MyFile####.mp4";

以及整数 0 到几百。 (它永远不会是一千或更多,但以防万一,四位数。 我想用整数值替换" ####",根据需要用前导零来匹配'#'字符的数量。 修改 s 或生成这样的新字符串的流畅 C++11/14 方法是什么?

通常我会使用char*字符串和snprintf()strchr()找到"#",但我认为我应该与现代时代并更频繁地使用std::string,但只知道最简单的用法。

修改 s 或生成这样的新字符串的流畅 C++11/14 方法是什么?

我不知道它是否足够光滑,但我建议使用 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
 }  

我会使用正则表达式,因为您使用的是C++14:

#include <iostream>
#include <regex>
#include <string>
#include <iterator>
int main()
{
    std::string text = "Myfile####.mp4";
    std::regex re("####");
    int num = 252;
    //convert int to string and add appropriate number of 0's
    std::string nu = std::to_string(num);
    while(nu.length() < 4) {
        nu = "0" + nu;
    }
    //let regex_replace do it's work
    std::regex_replace(std::ostreambuf_iterator<char>(std::cout),
                       text.begin(), text.end(), re, nu);
    std::cout << std::endl;
    return 0;
}

WHy 不使用 std::stringstream 并将其转换为字符串。

std::string inputNumber (std::string s, int n) {
   std::stringstream sstream;
   bool numberIsSet = false;
   for (int i = 0; i < s; ++i) {
      if (s[i] == '#' && numberIsSet == true)
         continue;
      else if (s[i] == '#' && numberIsSet == false) {
         sstream << setfill('0') << setw(5) << n;
         numberIsSet = true;
      } else
         sstream << s[i];
   }
   return sstream.str();
}

我可能会使用这样的东西

#include <iostream>
using namespace std;
int main()
{
    int SomeNumber = 42;
    std:string num = std::to_string(SomeNumber);
    string padding = "";
    while(padding.length()+num.length()<4){
        padding += "0";
    }
    string result = "MyFile"+padding+num+".mp4";
    cout << result << endl; 
   return 0;
}

当我玩它时,我的失控了,呵呵。

在其命令行上传递模式,例如:

./cpp-string-fill file########.jpg '####' test###this### and#this

#include <string>
#include <iostream>
#include <sstream>
std::string fill_pattern(std::string p, int num) {
    size_t start_i, end_i;
    for(
        start_i = p.find_first_of('#'), end_i = start_i;
        end_i < p.length() && p[end_i] == '#';
        ++end_i
    ) {
        // Nothing special here.
    }
    if(end_i <= p.length()) {
        std::ostringstream os;
        os << num;
        const std::string &ns = os.str();
        size_t n_i = ns.length();
        while(end_i > start_i && n_i > 0) {
            end_i--;
            n_i--;
            p[end_i] = ns[n_i];
        }
        while(end_i > start_i) {
            end_i--;
            p[end_i] = '0';
        }
    }
    return p;
}
int main(int argc, char *argv[]) {
    if(argc<2) {
        exit(1);
    }
    for(int i = 1; i < argc; i++) {
        std::cout << fill_pattern(argv[i], 1283) << std::endl;
    }
    return 0;
}

我可能会做这样的事情:

using namespace std;
#include <iostream>
#include <string>
int main()
{
    int SomeNumber = 42;
    string num = std::to_string(SomeNumber);
    string guide = "myfile####.mp3";
    int start = static_cast<int>(guide.find_first_of("#")); 
    int end = static_cast<int>(guide.find_last_of("#"));
    int used = 1;
    int place = end;
    char padding = '0';
    while(place >= start){
        if(used>num.length()){
            guide.begin()[place]=padding;
        }else{
            guide.begin()[place]=num[num.length()-used];
        }
        place--;
        used++;
    }
    cout << guide << endl; 
   return 0;
}