C和C++字符串删除等特定操作处理

本文介绍三种使用C语言从字符串中删除特定字符的方法:第一种直接在原字符串上操作;第二种开辟新内存空间逐字符拷贝;第三种同样不开辟新空间但采用不同循环方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 C字符串删除特定字符,实际上利用了函数重新修改了特定地址上的字符串,而且是按照添加的方式修改的!

void del_chr( char *s, char ch )
{
    char *t=s; //目标指针先指向原串头
    while( *s != '\0' //遍历字符串s
    {
        if ( *s != ch ) //如果当前字符不是要删除的,则保存到目标串中
            *t++=*s;
        s++ ; //检查下一个字符
    }
    *t='\0'//置目标串结束符。
}
void main()
{
    char str[]="***abcde***fghi***" ;
    del_chr(str, '*' );
    printf("str=【%s】\n", str );
}

方法二

在一个函数里面实现,但是要new char新开辟一块地址;

int main()
 {

     char str[] = "we are stu!";
     char *zcl = new char;
     char *cxl = zcl;
     int len = strlen(str);
     for (int i = 0; i < len; i++)
     {
         if (str[i] == 'w' || str[i] == 'e')
         {
             zcl = zcl;
         }
         else
         {
             *zcl = str[i];
             zcl++;
         }
     }
     *zcl = '\0';
     cout << cxl << endl;
    
 
     system("pause");
     return 0;
 }

方法三,沿用之前地址上的字符串,但是不能再跟方法二一样用for循环了,因为循环的index已经发生了改变!

 int main()
 {

     char str[] = "we are stu!";
     char *zcl = str;
     char *cxl = zcl;
     int len = strlen(str);
     int i = 0;
     while (str[i]!='\0')
     {
         if (str[i] == 'w' || str[i] == 'e')
         {
             zcl = zcl;
             i++;
         }
         else
         {
             *zcl = str[i];
             zcl++;
             i++;
         }
     }
     *zcl = '\0';
     cout << cxl << endl;
    
 
     system("pause");
     return 0;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值