Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In a C++14 program, I am given a string like

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

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?

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.

like image 646
DarenW Avatar asked Apr 19 '18 20:04

DarenW


People also ask

How do you add leading zeros to a string in C++?

Starting with C++20, we can use the formatting library to add leading zeros to the string. It provides the std::format function in the header <format> . With C++17 and before, we can use the {fmt} library to achieve the same. That's all about adding leading zeros to a string in C++.

How do you add a leading zero to a string?

You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

How do you add integers to a string in C++?

Using to_string() function The most commonly used approach to concatenate an integer to a string object in C++ is to call the std::to_string function, which can return the string representation of the specified integer.

How do you add an integer to a string?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.


1 Answers

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

I don't know if it's slick enough but I propose the use of std::transform(), a lambda function and reverse iterators.

Something like

#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
 }  
like image 71
max66 Avatar answered Nov 10 '22 11:11

max66