0

So I've been trying to solve the following problem to no avail:

Write a function called removeString to remove a specified number of characters from a character string. The function should take three arguments: the source string, the starting index number in the source string, and the number of characters to remove. So, if the array text contains the string "the wrong son", the call

removeString (text, 4, 6);

has the effect of removing the characters "wrong " (the word "wrong" plus the space that follows) from the array text. The resulting string inside text is then "the son".

I've tried looking up other solutions but all of them use the memcpy function which I'd like to avoid as it hasn't been introduced in my book yet and I'd rather not "cheat the system" so to speak.

My removeString function is as follows:

void removeString (char text[], int x, int y)
{
    char output[81];
    int i, z = 0;
        
    for ( i = 0; (i <= 81); i++) {
            
        if (z < (x-1) || z > (x+y-1) ) {
            output[z] = text[z];
            //printf("%i\n", z);
            z++;
        } else {
            z++;
        }
            
    }
        
}

int main(void)
{
    char s1[81] = "the wrong son";
    int startPoint = 4, runLength = 6;
    
    removeString(s1, startPoint, runLength);
    
    printf("The new text is as follows:\n");
    printf("%s\n", s1);
    
    return 0;
}

When I print out the value of "z" I see that it's skipping numbers, but for some reason it looks like its copying all of text[] into output[].

1
  • Your function doesn't change text (s1) because output is local to removeString. Related (though not necessarily duplicate): stackoverflow.com/questions/19696338/… Commented Nov 5, 2013 at 18:07

2 Answers 2

3

this will do the trick on the original string

for (;text[x];x++)
{
  text[x]=text[x+y];
}
Sign up to request clarification or add additional context in comments.

Comments

1
           output[z] = text[z];

It means that every element in the new array will be in the same index like the original one. Also, you need to get output as a parameter instead of declaring it locally:

void removeString (char text[], char output[], int x, int y)
{
    for(int i = 0; i < x; i++)
        output[i] = text[i];

    for (int i = y; text[i] != '\0'; i++)
        output[i - (y - x)] = text[i];

}

int main(void)
{
    char s1[81] = "the wrong son";
    char output[81];
    int startPoint = 4, runLength = 6;

    removeString(s1, output, startPoint, runLength);

    printf("The new text is as follows:\n");
    printf("%s\n", s1);

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.