2012-06-03 4 views
4

J'ai la chaîne suivante ID is a sample string remove to /0.10, je voudrais terminer avec le suivant: ID/0.10.Méthode plus propre pour supprimer une sous-chaîne de str in C

Voici ce que j'ai trouvé. Cependant, je suis à la recherche d'une façon plus propre/plus agréable de le faire.

#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; 
} 
+0

droite ce que je cherchais. Merci! – Kayla

Répondre

3

Après avoir déterminé a et b vous pouvez simplifier la memmove comme ceci:

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

Les calculs que vous faites sur les longueurs de chaîne ne sont pas vraiment nécessaires.

+0

Calcul de longueur excessif dans cette version. – Ruben

+0

ne sait pas "/ ID" –

+0

Veuillez corriger le crochet redondant à la fin de 'memmove()'. – pevik

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

Ou si vous aimez une version très dense

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 ++); 
+0

Etes-vous sûr que le comportement de 'while (* a ++ = * b ++);' est défini par C standard? – Ruben

+1

Je suis tout à fait sûr que les premières implémentations de strcpy utilisant ce fragment. Où voyez-vous un problème? (OK, vous devez ignorer l'avertissement) (voir aussi http://stackoverflow.com/questions/7962159/strcpy-implementation-method) –

+2

Sans les espaces, il s'agit en fait de K & R strcpy(): 'while (* a ++ = * b ++); – wildplasser

Questions connexes