Dar*_*enW 6 c++ stdstring c++14
在C++ 14程序中,我给了一个类似的字符串
std::string s = "MyFile####.mp4";
Run Code Online (Sandbox Code Playgroud)
和0到几百的整数.(它永远不会是一千个或更多,但只有四个数字.)我想####用整数值替换" ",根据需要使用前导零来匹配'#'字符数.什么是灵活的C++ 11/14修改s或生成这样的新字符串的方法?
通常我会使用char*字符串snprintf(),strchr()并找到" #",但我应该得到现代和std::string更频繁使用,但只知道它的最简单的用途.
什么是灵活的C++ 11/14修改s或生成这样的新字符串的方法?
我不知道它是否足够光滑,但我建议使用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
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我会使用正则表达式,因为你正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
我可能会用这样的东西
#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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1386 次 |
| 最近记录: |