C 删除字符串中的字符

标签 c string

我有一个程序要求输入一个字符串 (mystring) 和一个字符 (ch)。然后它从字符串 (mystring) 中删除所有输入的字符 (ch)。例如“abcabc”和char 'a' 那么结果应该是“bcbc”。 - 当我使用 scanf 时,如果字符串没有空格,程序运行良好。如果我输入“abc abc abc”,它只读取和处理前 3 个字母(直到空格)。 然后我被建议使用 gets(mystr);因为它可以读取所有的stirng。但是当我使用 gets 时,结果与输入字符串相同,没有任何反应。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100

int main(int argc, char *argv[])
{
   char mystr[N] ,result[N];
   char ch;
   int i,k;
   k=0;

   printf("enter string \n");   
   //gets(mystr);///////////////////////////
   //scanf("%s",&mystr);///////////////////
   printf("enter char \n");  
     scanf("%c",&ch);
     scanf("%c",&ch);

  for ( i = 0; i <= strlen(mystr); i++ )
  {
    if (mystr[i] != ch)
    {
      result[k]=mystr[i];
      k++;
    } 
  }
   puts(result);
   system("pause");
   return 0;
}

最佳答案

 scanf("%c",&ch);
 scanf("%c",&ch);

第二个 scanf 是你的问题。它会拾取您在要删除的字母后输入的换行符(并覆盖 ch 的先前值)。

摆脱它。

请注意,如手册页所述:

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

关于C 删除字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7859717/

相关文章:

Java : Index out of bound exception when creating a string with no matching consecutive characters

c - R 不会引用/找不到编译后加载的 C 代码

android - 如何在 C/C++ 中方便地发布算术溢出异常

ios - 缓慢的 Swift 字符串性能

python - 在 Python 中将 ASCII 字符转换为 Unicode FULLWIDTH 拉丁字母?

Javascript - 将字符串从某个字符拼接到下一个字符

c - 难以理解指针、动态分配和函数调用行为

c - 为什么 scanf 在写入字符串文字时没有按预期工作?

c - 如何重新设计此代码以避免转到

java - 将字符串变量转换为列表 [Groovy]