簡體   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