删除字符串A中与字符串B相同的字符

image

/**
 * file name:DelDestChar.c
 * author   : liaojx2016@126.com
 * date     : 2024-05-06
 * function : Delete string A alike to string B's charactor
 * note     : None
 * CopyRight (c)   2024  liaojx2016@126.com  Right Reseverd
 *
**/
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
/**
 *
 * func name      : func
 * function       : Delete string A alike to string B's charactor
 * parameter      : 
 *                      @strA :Address pointed to string A
 *                      @strA :Address pointed to string B
 * Return val      : Address pointed to modified string A
 * note            : None
 * author          : liaojx2016@126.com
 * date            : 2024-05-06
 * version         : V1.0
 * modify history  : None
 *
**/
char* func(const char*strA , const char *strB)
{
    char *str = ( char* )malloc( strlen(strA) );//用于存放strA删除后的字符串
    if(str == NULL)
    {
        perror("malloc failed\n");
        exit(-1);
    }
    str=strcpy( str,strA );
    //printf("str =%s\n",str);
    int i=0;//str的下标
    char *p;//备份每次循环改变后的str字符串

    //判断字符串B是否到达末尾
    while (*strB)
    {
        //printf("*strB=%c\n",*strB);
        //判断字符串B的当前字符是否属于字母(大写字母 or 小写字母)    
		if ( (*strB < 'A' || *strB > 'Z') && (*strB < 'a' || *strB > 'z') )
		{
			//如果字符串B的字符不是字母,则向后偏移
			strB++;
			continue;
		}
        i=0;
        p=str;
        //判断字符串p是否到达末尾
        while(*p)
        {
            //判断当前字符属于字母范围且大小写与字符串B当前的字符大小写相等
          if ( ( (*p > 'A' && *p < 'Z') || (*p > 'a' || *p < 'z') ) && (*p==*strB ||*p==*strB+32 ||*p==*strB-32 ))
            {
                //若成立,则不赋值,直接地址偏移
                p++;
            }
            else
            {
                //若不成立,直接赋值
                str[i++]=*p++;
            }
            //printf("i=%d\n",i);
            //printf("str=%s\n",str);
        }
        //此时字符串A中与字符串B的当前字符大小写相同的字符已删除
        str[i]='\0';    //将str的字符串加上结束标志、0
        //printf("***str=%s\n",str);
        strB ++;
    }
    return str;
}

int main(int argc, char const *argv[])
{
    char*strA="Hello world";
    char*strB="Loh";
    printf("strA =%s\n",strA);
    printf("strB =%s\n",strB);
    char *str=func(strA,strB);

    printf("str=%s\n",str);

    return 0;
}

测试输出结果:
image

posted @ 2024-05-06 21:51  沉舟道人  阅读(9)  评论(1编辑  收藏  举报