c++ - 字符串操作——需要更好的方法

标签 c++

我有一个要求,我需要从字符串中提取所需格式的数字,例如:

  • f001-->100
  • f100-->1
  • 2030-->302
  • 0203-->3020
  • 2031-->1302

所以上面的操作是:

  • 删除任何存在的 f 字符
  • 反转字符串
  • 从字符串中删除前导零

我写了一个在 C++ 中运行良好的代码:

int main(int argc,char* argv[])
{

string str1(argv[argc-1]);


reverse(str1.begin(),str1.end());
str1.erase(remove(str1.begin(),str1.end(),'f'),str1.end());
str1.erase(0,str1.find_first_not_of('0',0));

cout <<str1<<endl;

return 0;

}

有没有更好的方法来做同样的事情?

最佳答案

我想,下面的一个简单函数就可以完成这项工作

注意:- 这不是一个完整的程序。只是一个流程......它将解析字符串一次而不是像你的情况那样解析 3 次。我绝对希望有更好的 C++ 风格的方法,并期待相同的方法。

foo(字符* str) {

int 状态=0;

int len=strlen(str);

for(i=len-1; i>=0; i++) {

if(state==0 && str[i]!='0') { //Ignore trailing zeros
    state=1;
}
else if(stare==1) {
    if(str[i]=='f')
        break;
    //Reverse logic here, just store the char in a heap as it comes which will be returned after the for finishes
}  

关于c++ - 字符串操作——需要更好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8395617/

相关文章:

C++ 理解 vector 创建的 size_t 行为

c++ - 为什么 const volatile 引用不能绑定(bind)到右值引用?

c++ - 实现代码来模拟 C++ 中不确定的有限自动机

C++ friend 函数/类使用?

c++ - 如何为 reference_wrapper 的 STL 容器设置初始大小?

c++ - 存在 ARM GNU 编译器 -j[jobs] 选项

c++ - 将证书文件复制到另一个位置

c++ - binary_search 与 std::pair 使用自定义运算符

c++ - OpenCV VideoWriter 帧率问题

c++ - 如何将 GUID 值分配给变量?