如何用'*'替换字符串中的两个a [英] How do I replace two a's in a string with an '*'
问题描述
嘿伙计们,对于我的任务,我必须用C中未知输入长度的字符串替换两个a'和'*'。挑战是我只允许使用getchar()和putchar()函数。
使用数组它会更容易,但我甚至不允许使用它。
我尝试过:
Hey guys so for my assignment I have to replace two a's with an '*' from a string of unknown input length in C. The challenge is I am only allowed to use the getchar() and the putchar() function.
With an array it would have been easier but I am not even allowed to use that.
What I have tried:
#include <stdio.h>
int ch;
int main()
{
while ((ch = getchar()) !=EOF && ch != '\n' ) {
if(ch=='a'){
if(ch=='a'){
ch='*';
}
}
putchar(ch);
}
putchar('\n');
return 0;
}
推荐答案
此代码错误,需要重写
This code is wrong and need rewrite
if(ch=='a'){
if(ch=='a'){
ch='*';
}
}
putchar(ch);
根据作业,当你遇到'a'时,你知道只有当你知道下一个字母时才该做什么。
你需要一个变量来告诉你是否有'a'等待。
如果'a'被搁置,你需要调整代码来处理。
代码如下:
As per assignment, when you encounter an 'a', you know what to do only when you know the next letter.
You need a variable to tell you if you have an 'a' on hold or not.
And you need to adapt the code to handle if a 'a' is on hold or not.
The code will look like:
if(ch=='a'){
if (a 'a' is on hold) {
putchar('*');
reset number of 'a' in hold
}
else {
add a 'a' in hold
}
}
else {
if (a 'a' is on hold) {
...
}
...
}
[更新]
[Update]
你可以解释一下你的意思吗?保持和保持英语不是我的第一语言
could you please explain what you mean by "in hold" and "on hold" english is not my first language
样本输入
Sample input
Input on Hold Output
b b
a a
n a n
a a
a *
a a
n a n
a a
\n a \n
您可以将'暂停'翻译为等待下一个输入。换句话说:你不知道怎么处理'a',直到你知道是否有第二个'a'。
You can translate 'on hold' as waiting for next input. Said otherwise: you don't know what to do with a 'a' until you know if there is a second 'a'.
这篇关于如何用'*'替换字符串中的两个a的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!