简体   繁体   中英

Repeatedly removing and replacing the occurence of a substring from the input string code is not working

I've been working on this problem:

Functions – Remove foo

Write a program to find the new string after repeatedly removing the occurence of the substring foo from the input string using functions by repeatedly replacing each occurence of 'foo' by 'oof'.

Refer function specifications for the function details.

The function accepts a pointer to a string.

 void manipulate(char * a)

Input and Output Format:

Input consists of a string. Assume that all characters in the string are lowercase letters and the maximum length of the string is 100.

Refer sample input and output for formatting specifications.

All text in bold corresponds to input and the rest corresponds to output.

Sample Input and Output:

 Enter the input string akhfoooo The output string is akhoooof

Function Definitions:

 void manipulate (char * a)

Here is my code:

#include <stdio.h>
#include <string.h>
void manipulate (char *a){
    int i;
    char b[3]="foo";
    for (i=0;i<strlen(a);i++){
        if (strncmp(a+i,b,3)==0){
            a[i]='o';
            a[i+1]='o';
            a[i+2]='f';
            manipulate (a);
        } 
    }
 printf ("%s",a);}
int main(){
    char string[50];
    printf ("Enter the input string\n");
    scanf ("%s",string);
    manipulate (string);
    return 0;
}

Can someone tell me how to edit this code in a manner that it gives the right output?

Print out the manipulated string in main when manipulate returns. If you print the string in every call to manipulate, you will get what you see, which is all of the intermediate results one after another.

Also, you really should print out a newline at the end of every printf (unless you know for sure that the next printf should be on the same line. So your printf call should look like this:

printf("%s\n", string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM