我有一个充满 * 字符的数组。我需要将数组中的任何字符替换为用户输入的另一个字符。是否可以?我将不胜感激任何建议。谢谢
#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/