如何在C语言中从字符串中移除多个字符?
实现移除多个指定字符的修改方案
你只需要调整两个地方:一是设置包含多个字符的symbol变量,二是修改remove_character函数里的字符判断逻辑,让它检查当前字符是否属于要移除的字符集合。
1. 设置多字符的symbol变量
直接把symbol定义成包含所有要移除字符的字符串即可,比如你想移除!和',就写成:
char symbol[] = "!'";
2. 修改remove_character函数的判断逻辑
原来的代码只判断了是否等于*remove(即remove字符串的第一个字符),现在需要改成检查当前字符是否在整个remove字符串中,下面提供两种实现方式:
方案一:用标准库函数strchr简化判断
利用strchr可以快速查找字符是否在目标字符串中,修改后的函数代码:
#include <string.h> #include <stdio.h> // 别忘了加这个,不然printf会报错 void remove_character(char *string, char *remove){ int position = 0; while (string[position] != '\0') { // 检查当前字符是否在要移除的集合中 if (strchr(remove, string[position]) != NULL){ int newposition = position; // 移除该字符,后续字符整体前移 while (string[newposition] != '\0') { string[newposition] = string[newposition+1]; newposition++; } // 移除后当前位置要重新检查新字符,所以position不递增 } else { position++; } } }
方案二:手动遍历remove字符串判断
如果不想依赖标准库函数,也可以自己写循环完成判断:
#include <stdio.h> void remove_character(char *string, char *remove){ int position = 0; while (string[position] != '\0') { int need_remove = 0; // 遍历要移除的字符集合,匹配当前字符 for (int i = 0; remove[i] != '\0'; i++){ if (string[position] == remove[i]){ need_remove = 1; break; } } if (need_remove){ int newposition = position; while (string[newposition] != '\0') { string[newposition] = string[newposition+1]; newposition++; } } else { position++; } } }
测试效果
修改main函数里的symbol后,比如:
int main(void){ char s[] = "Thi!s is s!ome tex!t that we'!ll check for plagiarism"; char symbol[] = "!'"; printf("%s\n", s); remove_character(s, symbol); printf("%s\n", s); return(0); }
运行后输出会变成:
Thi!s is s!ome tex!t that we'!ll check for plagiarism This is some text that we'll check for plagiarism
内容的提问来源于stack exchange,提问作者Wolo
相关产品推荐
相关产品推荐

