首页 > 解决方案 > 我尝试编写一个函数来删除字符串中的所有字符(期望字母表)。但我的代码有问题

问题描述

我尝试编写一个函数来删除字符串中的所有字符(期望字母表)。但是我的代码中有一个错误,好像我输入 hello123string23gg3 输出是>> hello2string3gg 所以它只删除了第一个特殊宪章所以我想知道错误是什么

#include<stdio.h>
void remove_all_except_alph(char str[]);
#define size 100
int main()
{
    char s[size];

    printf("Enter a string: ");
    gets(s);
    remove_all_except_alph(s);
    printf("the string after removing : ");
    puts(s);
    return 0;
}
void remove_all_except_alph(char str[])
{
    int i, j;
    for(i = 0; str[i] != '\0'; ++i)
    {
        if( !((str[i] >= 65 && str[i] <= 90) || (str[i] >= 97 && str[i] <= 122)) &&  (str[i] != '\0') )
        {
            /* Enter here in case the element is not alphabet and it is not equals to null */
            for(j = i; str[j] != '\0'; ++j)
            {
/* remove this not alphabet character by making each element equals to the value of the next element */
                str[j] = str[j+1];
            }
        }
    }}

标签: cstring

解决方案


在移动字符的情况下,您不应该增加 i 。如果您增加 i,您将跳过一个字符

for(i = 0; str[i] != '\0'; ++i)
    {
        if( !((str[i] >= 65 && str[i] <= 90) || (str[i] >= 97 && str[i] <= 122)) &&  (str[i] != '\0') )
        {
            /* Enter here in case the element is not alphabet and it is not equals to null */
            for(j = i; str[j] != '\0'; ++j)
            {
/* remove this not alphabet character by making each element equals to the value of the next element */
                str[j] = str[j+1];
            }
            i--;
        }
    }}

推荐阅读