c - 将数组的字符元素替换为用户输入输入的另一个字符

标签 c arrays input replace character

我有一个充满 * 字符的数组。我需要将数组中的任何字符替换为用户输入的另一个字符。是否可以?我将不胜感激任何建议。谢谢

    #include <stdio.h>
    #include <string.h>

    strreplace(char[],char,char);
    int main()
    {
        char s[17]="* * * *\n* * * * ";
        char chr,repl_chr;
        printf("%s", s);
        printf("\nEnter character to be replaced: ");
        chr=getchar();
        fflush(stdin);
        printf("\nEnter replacement character: ");
        repl_chr=getchar();
        printf("\nModified string after replacement is: \n");
        strreplace(s,chr,repl_chr);
        getch();
        return 0;
   }



   strreplace(char s[], char chr, char repl_chr)
   {
      int i=0;
      while(s[i]!=' ')
      {
           if(s[i]==chr)
           {
               s[i]=repl_chr;
           }
           i++;
      }
      puts(s);
      return 0;
  }

最佳答案

更改您的strreplace,以便将参数chr 转换为索引。

int strreplace(char s[], char chr, char repl_chr)
{
    int i = 0;

    // Convert the input char into an index.
    // Note that 1 is subtracted to make the index zero-based.
    // Remember that the user entered a one-based index.
    int index = chr - '0' - 1;
    if ((index < 0) || (index >= 8))
    {
        // Out of bounds.
        return -1;
    }
    while (s[i] != '\0')
    {
        if ((i/2) == index)
        {
            s[i] = repl_chr;
        }

        // Note: since every second char is to get ignored,
        // the increment must actually be 2 here.
        i += 2;
    }
    puts(s);
    return 0;
}

关于c - 将数组的字符元素替换为用户输入输入的另一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39934031/

相关文章:

c - 我有一个程序无法在 Ubuntu 上运行,但可以在 Windows 上运行

python - 如何在Python中从文本文件传递输入参数?

Bash 输入而不暂停脚本?

c++ - sizeof() 运算符的行为

c - 从结构中的文本文件中读取文本

c - 程序从字符串中删除特殊字符和数字并仅打印英文字母

java - 为什么打印 Integer array Object 给出哈希码而 char array object 在 java 中给出值?

java - 从另一个库调用一个库函数

c++ - Fftw3 库和计划重用

javascript - 使用函数将多个输入推送到单独的 div 中?