2011-01-28 18 views
10

Ho una funzione C, che prende una stringa chiamata 'buffer' e la analizza, abbinerà le parole chiave e la userà per assegnare i valori in una struttura.Rimozione della sottostringa da una stringa?

Tuttavia, alcune parole chiave voglio ignorare completamente.

Questo programma analizza i file VCard (.vcf, biglietti da visita virtuali).

Ecco un buffer di linea del campione potrebbe fornire:

FN;CHARSET=UTF-8:David Celery 

FN è una parola chiave im interessati, e David Sedano è il valore associato a FN.

Tuttavia, CHARSET = UTF-8 è qualcosa a cui non mi interessa affatto.

Quindi la mia domanda è, c'è un modo per me di analizzare il mio buffer e semplicemente sostituire 'CHARSET = UTF-8 "con" ", in modo che non debba preoccuparsi di analizzarlo (e altre parole chiave simili voglio solo di ignorare)

Grazie,

+1

Cosa hai provato fino ad ora? E se stai lavorando con le stringhe in C, e non sei in grado di fare qualcosa di così semplice, ti suggerisco di prendere in considerazione l'uso di un linguaggio con supporto per le stringhe incorporato (ad es. C++, Java, C#, Python, Delphi ecc.) –

risposta

11

hanno uno sguardo ad una soluzione semplice ANSI C come:

void removeSubstring(char *s,const char *toremove) 
{ 
    while(s=strstr(s,toremove)) 
    memmove(s,s+strlen(toremove),1+strlen(s+strlen(toremove))); 
} 
+0

Ricevo avvisi e un segfault che tenta di utilizzare questo codice. C'è un errore da qualche parte? Sto usando il99 se è importante. – Blackbinary

+8

Se hai memorizzato 'strlen (toremove)' sarebbe più efficiente - non c'è bisogno di determinarlo due volte per loop. La prestazione di – ThiefMaster

+0

non era la domanda; questo codice funziona bene anche per più occorrenze, penso che sia tuo o il tuo problema del compilatore – user411313

2

Qualcun altro ha trovare una stringa di C e la funzione che si potrebbe trovare utile here sostituire

edit:.. incluso frammento di codice dal link qui sotto, come da richiesta di commento

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
/* 
* Description: 
* Find and replace text within a string. 
* 
* Parameters: 
* src (in) - pointer to source string 
* from (in) - pointer to search text 
* to (in) - pointer to replacement text 
* 
* Returns: 
* Returns a pointer to dynamically-allocated memory containing string 
* with occurences of the text pointed to by 'from' replaced by with the 
* text pointed to by 'to'. 
*/ 
char *replace(const char *src, const char *from, const char *to) 
{ 
    /* 
    * Find out the lengths of the source string, text to replace, and 
    * the replacement text. 
    */ 
    size_t size = strlen(src) + 1; 
    size_t fromlen = strlen(from); 
    size_t tolen = strlen(to); 
    /* 
    * Allocate the first chunk with enough for the original string. 
    */ 
    char *value = malloc(size); 
    /* 
    * We need to return 'value', so let's make a copy to mess around with. 
    */ 
    char *dst = value; 
    /* 
    * Before we begin, let's see if malloc was successful. 
    */ 
    if (value != NULL) 
    { 
     /* 
     * Loop until no matches are found. 
     */ 
     for (;;) 
     { 
     /* 
      * Try to find the search text. 
      */ 
     const char *match = strstr(src, from); 
     if (match != NULL) 
     { 
      /* 
      * Found search text at location 'match'. :) 
      * Find out how many characters to copy up to the 'match'. 
      */ 
      size_t count = match - src; 
      /* 
      * We are going to realloc, and for that we will need a 
      * temporary pointer for safe usage. 
      */ 
      char *temp; 
      /* 
      * Calculate the total size the string will be after the 
      * replacement is performed. 
      */ 
      size += tolen - fromlen; 
      /* 
      * Attempt to realloc memory for the new size. 
      */ 
      temp = realloc(value, size); 
      if (temp == NULL) 
      { 
       /* 
       * Attempt to realloc failed. Free the previously malloc'd 
       * memory and return with our tail between our legs. :(
       */ 
       free(value); 
       return NULL; 
      } 
      /* 
      * The call to realloc was successful. :) But we'll want to 
      * return 'value' eventually, so let's point it to the memory 
      * that we are now working with. And let's not forget to point 
      * to the right location in the destination as well. 
      */ 
      dst = temp + (dst - value); 
      value = temp; 
      /* 
      * Copy from the source to the point where we matched. Then 
      * move the source pointer ahead by the amount we copied. And 
      * move the destination pointer ahead by the same amount. 
      */ 
      memmove(dst, src, count); 
      src += count; 
      dst += count; 
      /* 
      * Now copy in the replacement text 'to' at the position of 
      * the match. Adjust the source pointer by the text we replaced. 
      * Adjust the destination pointer by the amount of replacement 
      * text. 
      */ 
      memmove(dst, to, tolen); 
      src += fromlen; 
      dst += tolen; 
     } 
     else /* No match found. */ 
     { 
      /* 
      * Copy any remaining part of the string. This includes the null 
      * termination character. 
      */ 
      strcpy(dst, src); 
      break; 
     } 
     } 
    } 
    return value; 
} 
void test(const char *source, const char *search, const char *repl) 
{ 
    char *after; 
    after = replace(source, search, repl); 
    printf("\nsearch = \"%s\", repl = \"%s\"\n", search, repl); 
    if (after != NULL) 
    { 
     printf("after = \"%s\"\n", after); 
     free(after); 
    } 
} 
int main(void) 
{ 
    const char before[] = "the rain in Spain falls mainly on the plain"; 
    printf("before = \"%s\"\n", before); 
    test(before, "the", "THEE"); 
    test(before, "the", "A"); 
    test(before, "cat", "DOG"); 
    test(before, "plain", "PLANE"); 
    test(before, "ain", "AINLY"); 
    return 0; 
} 
/* my output 
before = "the rain in Spain falls mainly on the plain" 
search = "the", repl = "THEE" 
after = "THEE rain in Spain falls mainly on THEE plain" 
search = "the", repl = "A" 
after = "A rain in Spain falls mainly on A plain" 
search = "cat", repl = "DOG" 
after = "the rain in Spain falls mainly on the plain" 
search = "plain", repl = "PLANE" 
after = "the rain in Spain falls mainly on the PLANE" 
search = "ain", repl = "AINLY" 
after = "the rAINLY in SpAINLY falls mAINLYly on the plAINLY" 
*/ 

Spero che questo aiuti.

0

Dai un'occhiata ai metodi in string.h.

Esempio: (e CodePad)

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

int main() 
{ 
    const char * source = "FN;CHARSET=UTF-8:David Celery"; 
    const char * newBegin = strrchr(source, ':'); 
    if (!newBegin) 
    { 
     puts("Error!"); 
     return -1; 
    } 
    newBegin++; 
    puts(newBegin); 
    return 0; 
} 
0

invece di rimuoverli, si potrebbe semplicemente ignorarli, per esempio come this:

#define KEY_TO_IGNORE "CHARSET=UTF-8" 

char key[80]; 
char value[80]; 
char *text = "FN;CHARSET=UTF-8:David Celery"; 

sscanf(text, "%2s;" KEY_TO_IGNORE ":%s", key, value); 

printf("key: %s, value: %s\n", key, value); 
+0

Non pensavo che stessimo cercando di risolvere tutti i problemi del mondo, basta dare suggerimenti per avvicinarsi, ma YMMV. – jlehr

Problemi correlati