ImpurestClub
ImpurestClub

Reputation: 303

Copying part of a character array to another array in C

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[].

Upvotes: 0

Views: 1503

Answers (2)

SHR
SHR

Reputation: 8333

this will do the trick on the original string

for (;text[x];x++)
{
  text[x]=text[x+y];
}

Upvotes: 3

LeeNeverGup
LeeNeverGup

Reputation: 1114

           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;
}

Upvotes: 1

Related Questions