繁体   English   中英

从字符串 C 中删除字符

[英]Removing char from string C

我正在学习 C 现在我需要制作一个程序来删除我将从字符串中输入的字符。 我看过一个算法,我写了这段代码

#define MAX_LEN 200
int main()
{
    char str[MAX_LEN];
    char rem;
    int i = 0;
    
    printf("Enter the setence:");
    gets(str);
    printf("\nEnter the char to remove");
    rem = getchar();
    char* pDest = str;
    char* pS= str;
    printf("sent:\n%s", str);

    while (str[i]!='\0'){
        if (*pDest != rem) {
            *pDest = *pS;
            pDest++;
            pS++;
        }
        else if (*pDest == rem) {
            pS++;
        }
        i++;
    }
    *pDest = '\0';
    while (str[i] != '\0') {
        printf("number%d", i);
        putchar(str[i]);
        printf("\n");
        i++;
    }
}

但它什么也不返回,就像 str 得到的值一样,我认为 \0 并且什么也不返回。 你能帮我找出问题吗?

使用函数!!

如果destNULL那么这个 function 将修改字符串str否则,它将把删除ch的字符串放在dest中。

它返回对已删除字符的字符串的引用。

char *removeChar(char *dest, char *str, const char ch)
{
    char *head = dest ? dest : str, *tail = str;

    if(str)
    {
        while(*tail)
        {
            if(*tail == ch) tail++;
            else *head++ = *tail++;
        }
        *head = 0;
    }
    return dest ? dest : str;
}


int main(void)
{
    char str[] = "ssHeslsslsos sWossrlssd!ss";

    printf("Removal of 's' : `%s`\n", removeChar(NULL, str, 's'));
}

我刚刚添加了新的 char 数组char dest[MAX_LEN]来存储带有已删除符号的字符串:

 #define MAX_LEN 200
    int main()
    {
        char str[MAX_LEN];
        char rem;
        int i = 0;
        
        printf("Enter the setence:");
        gets(str);
        printf("\nEnter the char to remove");
        rem = getchar();
        char dest[MAX_LEN] = "\0";
        char* pDest = dest;
        char* pS = str;
        printf("sent:\n%s", str);
    
        while (str[i]!='\0')
        {
            if (*pS != rem) 
            {
                *pDest = *pS;
                pDest++;
                pS++;
            }
            else if (*pS == rem) 
            {
                pS++;
            }
            i++;
        }
        i = 0;
        printf("\nres:\n %s \n", dest);
        while (dest[i] != '\0') {
            printf("number%d", i);
            putchar(dest[i]);
            printf("\n");
            i++;
        }
    }

通过字符串对 go 使用数组样式索引会更容易。 例如使用str[i] = str[i + 1]而不是*pstr = *other_pstr 我留下了这个不完整的方法,因为这看起来像家庭作业。

int main()
{
    char str[] = "0123456789";
    char ch = '3';
    for (int i = 0, len = strlen(str); i < len; i++)
        if (str[i] == ch)
        {
            for (int k = i; k < len; k++)
            {
                //Todo: shift the characters to left 
                //Hint, it's one line
            }
            len--;
        }
    printf("%s\n", str);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM