Robin
Robin

Reputation: 129

Remove substring of string

So i was doing some coding exercice on Talentbuddy (for those who know), and i cant get why i cant finish this one. The exercice is removing a substring from a string, given as input the string, the position P where beginning to remove characters and N the number of characters needed to be remove.

Here is what i've done :

#include <stdio.h>
#include <unistd.h>

void remove_substring(char *s, int p, int n) 
{
    int idx;

    idx = -1;
    while (s[++idx] != '\0')
       write(1, &s[idx == p - 1 ? idx + n : idx], 1);
}

When the input is "abcdefghi", P = 9 and N = 1, the result given is "abcdefgh" exactly the same as the one i get with my function. But TalentBuddy keep saying me that my output is wrong and i dont thing he (talentbuddy) is wrong. Maybe there is a blank space or something between the "h" and the '\0'. But i cant figure it cause when i add another write(1, "END", 3) at the end it appears like "abcdefghEND".

Upvotes: 0

Views: 1467

Answers (2)

asio_guy
asio_guy

Reputation: 3767

If the question is exclusively for strings( NULL Terminated ) Why can't this be as simple as this, unless it is a homework.

void removesubstr( const char *string, const char *substring )
{
        char *p = strstr(string, substring);
        if(p)
        {
                strcpy(p,p+strlen(substring));
        }
}

Upvotes: 1

M Oehm
M Oehm

Reputation: 29116

Your problem is that you write something for every original index, even if it should be suppressed. What you write looks like abcdefgh, but it is abcdefgh<nul>, where the terminal doesn't render the <nul>.

You are mixing two methods here. Either filter out the removed substring:

void remove_substring(char *s, int p, int n) 
{
    int i = 0;

    p--;        /* convert to C-style index */

    while (s[i] != '\0') {
       if (i < p || i >= p + n) putchar(s[i]);
       i++;
    }
}

or skip the substring by jumping over it:

void remove_substring(char *s, int p, int n) 
{
    int i = 0;
    int l = strlen(s);

    while (i < l) {
        if (i + 1 == p) {
            i += n;
        } else {
            putchar(s[i++]);
        }
    }
}

You're trying to do a bit of both.

(I've avoided the awkward combination of prefix increment and starting at minus 1. And I've used putchar instead of unistd's write. And the termination by length is so you don't inadvertently jump beyond the terminating <nul>.)

Upvotes: 0

Related Questions