繁体   English   中英

替换C中字符串中的字符

[英]replacing a character in string in C

必须用另一个用户输入字符替换用户输入字符并打印字符串。 我究竟做错了什么 ?

#include<stdio.h>
#include<conio.h>
main()
{
int i;
char a,b,str[100];
printf("Enter the string");
gets(str);
//asking for replacement
printf("enter the character to be replaced");
scanf("%c",&a);
// which letter to replace the existing one
printf("enter the character to replace");
scanf("%c",&b);
for(i=0;str[i]!='\0';i++)
{
    if(str[i]==a)
    {
    str[i] = b;
    }
    else
    continue;
}
printf("the new string is");
puts(str);
}
scanf("%d",&a);

你得到一个整数? 不是角色吗? 如果是字符,则应使用%c而不是%d

在两个scanf()之间添加getchar()函数。

喜欢

#include<stdio.h>
main()
{
        int i;
        char a,b,str[100];
        printf("Enter the string");
        gets(str);
        //asking for replacement
        printf("enter the character to be replaced");
        scanf("%c ",&a);
        //Get the pending character.
        getchar();
        // which letter to replace the existing one
        printf("enter the character to replace");
        scanf("%c",&b);
        for(i=0;str[i]!='\0';i++)
        {
                if(str[i]==a)
                {
                        str[i] = b;
                }
                else
                        continue;
        }
        printf("the new string is");
        puts(str);
}

问题是当您输入一个字符并按Enter键时,换行符将充当一个字符,并在下一个scanf中获得。 为了避免使用getchar()

其他方式:

在字符的访问说明符前给空格以替换,

喜欢

scanf(" %c",&b);

但是在删除该getchar()

#include<stdio.h>
#include<conio.h>
int main() //main returns an int
{
int i;
char a,b,str[100];

printf("Enter the string\n");
fgets(str,sizeof(str),stdin);//gets is dangerous

printf("Enter the character to be replaced\n");
scanf(" %c",&a); //space before %c is not neccessary here

printf("Enter the character to replace\n");
scanf(" %c",&b); //space before %c is compulsory here
for(i=0;str[i]!='\0';i++)
{
    if(str[i]==a)
    {
    str[i] = b;
    }
    //else //This part is not neccessary
    //continue;
}
printf("The new string is ");
puts(str);
return 0; //main returns an int
}

我使用了fgets因为gets是危险的,因为它不能防止缓冲区溢出

scanf中, %c之前空格是跳过空格,即空格,换行等,而在第一个scanf则不需要,因为fgets也使用换行符并将其放入缓冲区。

else continue;原因else continue;的原因else continue; 不需要的是,循环将在到达循环主体末尾时检查条件。

我使用了int main()return 0因为按照最新的标准, 它应该

最后,您的程序中有一个未使用的头文件conio.h

试试这个,对我有用:

#include<stdio.h>
#include<conio.h>
main()
{
  int i;
  char a,b,str[100];
  printf("Enter the string: ");
  gets(str);
  //asking for replacement
  printf("enter the character to be replaced: ");
  a = _getch();
  printf("\n%c", a);
  // which letter to replace the existing one
  printf("\nenter the character to replace: ");
  b = _getch();
  printf("\n%c", b);

  for(i=0;str[i]!='\0';i++)
  {
    if(str[i]==a)
    {
      str[i] = b;
    }

    else
     continue;
  }
  printf("\nthe new string is: "); 
  puts(str);
}

您可以删除else块。 它不会影响任何东西。

暂无
暂无

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

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