替换C中字符串中的字符

时间:2014-12-17 13:58:58

标签: 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);
}

4 个答案:

答案 0 :(得分:2)

scanf("%d",&a);

你得到一个整数?不是一个角色?如果是角色,则应使用%c代替%d

答案 1 :(得分:1)

在两个getchar()之间添加scanf()个功能。

#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);
}

问题是当你给一个角色并按下回车时,换行将作为一个角色,它将在下一个scanf中获得。为了避免getchar()正在使用。

另一种方式:

在要替换的字符上的访问说明符之前给出空格

scanf(" %c",&b);

但在删除之前getchar()

答案 2 :(得分:1)

#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 is dangerous,因为它不会阻止buffer overflows

space before %c in the scanf是要跳过空白,即空格,换行等,而第一个scanf中不需要fgets也消耗新的空格行字符并将其放入缓冲区。

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

我已使用int main()return 0,因为根据最新标准,it should

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

答案 3 :(得分:0)

试试这个,它对我有用:

#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块。它不会影响任何事情。