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.
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++.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With