4

I have the following string ID is a sample string remove to /0.10, I would like to end up with the following: ID/0.10.

This is what I came up with. However, I'm looking for a cleaner/nicer way of doing this.

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

int main ()
{
    char str[] = "ID is a sample string remove to /0.10";
    char *a = strstr(str, "ID");
    char *b = strrchr (str, '/');
    if (a == NULL)
        return 0;
    if (b == NULL)
        return 0;

    int p1 = a-str+2;
    int p2 = b-str;
    int remL = p2 - p1;
    int until = (strlen(str) - p1 - remL) +1;

    memmove (str+p1, str+(p1+remL), until);
    printf ("%s\n",str);
    return 0;
}
Kayla
  • 899
  • 2
  • 6
  • 16

2 Answers2

3

After determining a and b you can simplify the memmove like this:

char str[] = "ID is a sample string remove to /0.10";
char *a = strstr(str, "ID");
char *b = strrchr (str, '/');
if ((a == NULL) || (b == NULL) || (b < a))
    return 0;

memmove(a+2, b, strlen(b)+1);

The calculations you do on the string lengths are not really necessary.

sth
  • 222,467
  • 53
  • 283
  • 367
1
#include <stdio.h>
#include <string.h>

int main ()
{
 char str[] = "ID is a sample string remove to /0.10";
 char *a = strstr(str, "ID");
 char *b = strrchr (str, '/');
 if (a == NULL || b == NULL)
    return 0;
 int dist = b - a; 
 if (dist <= 0) return 0;  // aware "/ ID"

 a += 2;
 while (*a ++ = *b ++);

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

 return 0;
}

Or if you like a very dense version

 char str[] = "ID is a sample string remove to /0.10";
 char *a = strstr(str, "ID");
 char *b = strrchr (str, '/');
 if (a == NULL || b < a) return 0; // no need to test b against NULL, implied with <
 a ++;
 while (*(++ a) = *b ++);
stefan bachert
  • 9,413
  • 4
  • 33
  • 40
  • Are you sure that behavior of `while (*a ++ = *b ++);` is defined by C standard? – Ruben Jun 03 '12 at 15:38
  • 1
    I am quite sure that early implementations of strcpy using that fragment. Where do you see a problem? (OK, you have to ignore the warning) (see also http://stackoverflow.com/questions/7962159/strcpy-implementation-method) – stefan bachert Jun 03 '12 at 15:42
  • 2
    Without the spaces, it is actually the K&R strcpy(): `while (*a++ = *b++);`. – wildplasser Jun 03 '12 at 15:45
  • @stefanbachert, seems like it's ok. – Ruben Jun 03 '12 at 16:01