How do I replace two a's in a string with an '*'

Apr 14, 2018
2
0
10
0
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. I am just allowed to use loops and ifs.


This is what I have tried. But it replaces all the a's with '*'.


This is what I have so far.

Code:
#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;
}
Is this even the right approach?
It just replaces all the a's with a '*'. But it should only replace two a's with a '*'.
Could someone help me or at least lead me to the right solution?
Thank you in advanc.
 

alexoiu

Honorable
Not working in C, but...
Initialise the integer i=0 and try including in the loop the condition i<2 for ending it (so either reaching the end of the string, or i<2) and apart from replacing a with * increment also i:
if(ch='a') { ch='*' and i++.
 
Apr 14, 2018
2
0
10
0


Hi thank you for your answer
but I am not quite sure what you mean by i<2
I tried it but I am not getting to the solution
 

gigantusmagnus

Prominent
Dec 22, 2017
19
0
590
6
the first 2 a's? you can add a counter value at for function, and add if the counter is 2 or more, the function stops

I don't remember much about C's codes

but its like this iirc

int a = strlen(string);

for(int i = 0; i<a; i++){
int cnt = 0;

if (cnt != 2){

*your codes here

}
printf(*the final strings);
}
 

alexoiu

Honorable


#include <stdio.h>
int ch;
int main()
int i=0
{
while ((ch = getchar()) !=EOF && ch != '\n' || i==2)
{
if(ch=='a')
{
if(ch=='a')
{
ch='*';
i++;
}
}
putchar(ch);
}
putchar('\n');
return 0;
}

Something like that. Not sure about the syntax...
 
Thread starter Similar threads Forum Replies Date
K Apps General Discussion 1
rwayne Apps General Discussion 1
A Apps General Discussion 5
A Apps General Discussion 1
K Apps General Discussion 1
010010 Apps General Discussion 3
S Apps General Discussion 1
C Apps General Discussion 2
B Apps General Discussion 1
A Apps General Discussion 2
E Apps General Discussion 6
XAKEP Apps General Discussion 7
M Apps General Discussion 5
B Apps General Discussion 2
B Apps General Discussion 2
R Apps General Discussion 4
sergeyn Apps General Discussion 9
D Apps General Discussion 2
krahul44 Apps General Discussion 5
krahul44 Apps General Discussion 2

ASK THE COMMUNITY