omig0001 2021-05-21 16:08 采纳率: 84.1%
浏览 58
已采纳

C++:删除字符串中的所有空格操作 代码冗余

如下三行代码没用:

#define _CRT_SECURE_NO_WARNINGS

 if (it == (*str).end())
            break;

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;

string del_space(string *str) {
    string::iterator it = (*str).begin();
    while ((it = find(it, (*str).end(), ' ')) != (*str).end())
    {
        (*str).erase(it);
        if (it == (*str).end())
            break;
    }
    return *str;
}
  • 写回答

1条回答 默认 最新

  • bostonAlen 2021-05-21 16:20
    关注
    #include <iostream>
    using namespace std;
    void trim(string &s)
    {
        int index = 0;
        if( !s.empty())
        {
            while( (index = s.find(' ',index)) != string::npos)
            {
                s.erase(index,1);
            }
        }
     
    }
    int main()
    {
        
        cout << "-------------------------------------" << endl;
     
        string pri = "  7ter   09, jdhfd iere*- ddw     jjdjjdj     ";
        cout << "src string is : \"" << pri << "\"" << endl;
        trim(pri);
        cout << "after string is : \"" << pri << "\"" << endl;
     
        cout << "-------------------------------------" << endl;
     
        return 0;
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?