删除字符串中指定字符(双指针法)

#include<bits/stdc++.h>
using namespace std;

void delete_sc(string &s,char c)
{
    for(int i=0,j=0;i<=s.length();i++)   ///这得小于等于因为要拷贝'\0'
    {
        if(s[i]!=c)
        {
            s[j++]=s[i];
        }
    }
}

int main()
{
    string s="123455675";
    delete_sc(s,'5');
    cout<<s.length()<<endl;  ///和原来的s长度一样
    printf("%s",s.c_str());  ///这儿得用c输出方式,不能用cout<<s;  否则'\0'后的字符会输出
    return 0;
}

猜你喜欢

转载自blog.csdn.net/armerzu/article/details/82748631