SORU
23 NİSAN 2009, PERŞEMBE


C dize değiştirmek için işlevi nedir?

(Char *) bir dize belirli bir dize tüm olay bulmak istiyorum ve başka bir dize ile değiştirin. &Lt bunu başaran herhangi bir basit işlevi, bir dize görmüyorum.h>

CEVAP
23 NİSAN 2009, PERŞEMBE


İyileştirici yerel değişkenler çoğu ortadan kaldırmak gerekir. Tmp işaretçi strcpy dize yürümek zorunda olmadığından emin olmak için orada boş bulmak. tmp her aramadan sonra sonuç sonuna işaret ediyor. (Strcpy rahatsız edici olabilir neden için Shlemiel the painter's algorithm.)

Düzenleme: "tüm olaylar" ilk kez: bul fark etmedi

// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
    char *result; // the return string
    char *ins;    // the next insert point
    char *tmp;    // varies
    int len_rep;  // length of rep
    int len_with; // length of with
    int len_front; // distance between rep and end of last rep
    int count;    // number of replacements

    if (!orig)
        return NULL;
    if (!rep)
        rep = "";
    len_rep = strlen(rep);
    if (!with)
        with = "";
    len_with = strlen(with);

    ins = orig;
    for (count = 0; tmp = strstr(ins, rep);   count) {
        ins = tmp   len_rep;
    }

    // first time through the loop, all the variable are set correctly
    // from here on,
    //    tmp points to the end of the result string
    //    ins points to the next occurrence of rep in orig
    //    orig points to the remainder of orig after "end of rep"
    tmp = result = malloc(strlen(orig)   (len_with - len_rep) * count   1);

    if (!result)
        return NULL;

    while (count--) {
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front)   len_front;
        tmp = strcpy(tmp, with)   len_with;
        orig  = len_front   len_rep; // move to next "end of rep"
    }
    strcpy(tmp, orig);
    return result;
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • B4ROK

    B4ROK

    1 EKİM 2008
  • knopik96

    knopik96

    7 Mayıs 2011
  • Sergio Lafuente Rubio

    Sergio Lafue

    11 Aralık 2008