我有一个充满*字符的数组。我需要将数组中的任何字符替换为用户输入的另一个字符。可能吗?我会感激任何建议。谢谢
#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;
}
答案 0 :(得分: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;
}
答案 1 :(得分:0)
尝试将循环中的while(s[i]!=' ')
更改为
while (s[i] != '\0')
检查您是否已到达字符串的末尾
int strreplace(char s[], char chr, char repl_chr);
int main(void)
{
char s[17] = "* * * *\n* * * * ";
char chr, repl_chr;
printf("%s", s);
printf("\nEnter character to be replaced: ");
scanf("%c", &chr);
printf("\nEnter replacement character: ");
scanf(" %c", &repl_chr);
printf("\nModified string after replacement is: \n");
strreplace(s, chr, repl_chr);
return 0;
}
int strreplace(char s[], char chr, char repl_chr)
{
int i = 0;
while (s[i] != '\0') {
if (s[i] == chr)
s[i] = repl_chr;
i++;
}
puts(s);
return 0;
}
输出:
* * * *
* * * *
Enter character to be replaced: *
Enter replacement character: B
Modified string after replacement is:
B B B B
B B B B