lundi 20 avril 2015

Repeatedly removing and replacing the occurence of a substring from the input string

I have this homework question : Write a C 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'.

This is my code:

#include <stdio.h>
#include <string.h>

void manipulate(char * a)
{
    int i, flag = 0;
    char newstr[100];

    for (i = 0; a[i] != '\0'; i++) {
        if (a[i] == 'f') {
            if ((a[i + 1] != '\0') && (a[i + 1] == 'o')) {
                if ((a[i + 2] != '\0') && (a[i + 2] == 'o')) {
                    i += 3;
                    flag++;
                }
            }
        }
        newstr[i] = a[i];
    }

    for (i = 0; i < flag; i++) {
        strcat(newstr, "oof");
    }

    printf("\nThe output string is %s", newstr);
}

int main()
{
    char a[100];

    printf("Enter the input string");
    scanf("%s",a);
    manipulate(a);

    return 0;
}

I think something is wrong with my code because the expected output is :

Enter the input string
akhfoooo
The output string is akhoooof

But my Actual output is :

Enter the input string
akhfoooo
The output string is akhoof

Could you please rectify the errors in my code?

Aucun commentaire:

Enregistrer un commentaire