[英]c programming beginner (arrays)
The question asks to input a sentence (up to 20 characters).问题要求输入一个句子(最多 20 个字符)。 If for any part of the input there contains the word bad, it is replaced with ---.
如果输入的任何部分包含单词 bad,则将其替换为 ---。 For example, input bad dog would output: --- dog, another example is input: bade and output: ---e.
例如输入 bad dog 会输出:--- dog,另一个例子是 input: bade 和 output: ---e。
I was only able to set up the array.我只能设置阵列。
#include <stdio.h>
main()
{
int c, i;
int counts[20];
for (i = 0; i <= 19; i=i+1)
{
counts[i] = 0;
}
c = getchar();
while (c!= '\n')
{
if ()
}
}
#include <stdio.h>
#include <string.h>
int main(){
char sentence[20+1];
char *p;
scanf("%20[^\n]", sentence);
if(NULL!=(p = strstr(sentence, "bad"))){//only once!,,
memcpy(p, "---", 3);
}
printf("%s\n", sentence);
return 0;
}
I modified your example to a simple and basic program .Try to understand it我将您的示例修改为一个简单而基本的程序。尝试理解它
#include <stdio.h>
#include <string.h>
void main()
{
int len,i;
char counts[20];
printf("enter the string (string length must be less than 20 characters) \n");
printf("and hit enter button after a string is entered\n");
i=0; // Data length count
do
{
counts[i]=getchar();
i++
}while(counts[i] != '\n');
i--;
len=i;
counts[i]='\0'; // Terminate string with null character
for(i=0;i<(len-2);i++) // Checks entire string for the word "bad" and if found it is replaced by "---"
{
if(counts[i] == 'b')
{
if(counts[i+1] == 'a'
{
if(counts[i+2]='d';
{
counts[i] ='-';
counts[i+1]='-';
counts[i+2]='-';
}
}
}
}
for(i=0;i<len;i++) // Displays the result
putchar(counts[i]);
getch();
}
Try the below code试试下面的代码
#include <stdio.h>
main()
{
char c;
int i;
char counts[20] = { 0 };
for(i=0; (i<20) & (c!= '\n'); )
{
c = getchar();
if (c == 'b')
{
c = getchar();
if (c == 'a')
{
c = getchar();
if (c == 'd')
{
counts[i+2] = '-';
counts[i+1] = '-';
counts[i] = '-';
i=i+3;
continue;
}
else
{
counts[i+2] = c;
counts[i+1] = 'a';
counts[i] = 'b';
i=i+3;
continue;
}
}
else
{
counts[i+1] = c;
counts[i] = 'b';
i=i+2;
continue;
}
}
counts[i] = c;
i=i+1;
}
printf("new string: %s\n", counts);
}
> Blockquote
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.