c - 我尝试编写一个函数来删除字符串中的所有字符(期望字母表)。但我的代码有问题
问题描述
我尝试编写一个函数来删除字符串中的所有字符(期望字母表)。但是我的代码中有一个错误,好像我输入 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];
}
}
}}
解决方案
在移动字符的情况下,您不应该增加 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--;
}
}}
推荐阅读
- android - Android Studio、列表和 sqli-database
- google-apps-script - 是否可以将 Google 文档复制到 Google AppScript?
- javascript - 第一次使用 javascript 做一个不工作的答题器游戏
- android - Volley 首次加载活动时显示空错误
- javascript - 在以下场景中,setTimeOut 的闭包是如何形成的
- android - ANDROID STUDIO ERROR org.gradle.api.tasks.TaskExecutionException:任务执行失败
- python - 特定 id 的 TensorFlow 预测
- r - 查找每月添加的客户数量
- javascript - 在进行超链接之前验证数据表
- docker - 如何减少 Windows 上 Docker Linux 容器的默认 VM 内存