Tuesday, November 08, 2005

replacing characters

Replacing characters in a string

 

---------------------------code--------------------------------

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

 

/* Preconditions:

 * s, old and new are valid non-NULL pointers

 * strlen(old) >= 1

 */

char *replace(const char *s, const char *old, const char *new)

{

    char *ret, *sr;

    size_t i, count = 0;

    size_t newlen = strlen(new);

    size_t oldlen = strlen(old);

 

    if (newlen != oldlen) {

        for (i = 0; s[i] != '\0'; ) {

            if (memcmp(&s[i], old, oldlen) == 0)

                count++, i += oldlen;

            else

                i++;

        }

    } else

        i = strlen(s);

 

    ret = malloc(i + 1 + count * (newlen - oldlen));

    if (ret == NULL)

        return NULL;

 

    sr = ret;

    while (*s) {

        if (memcmp(s, old, oldlen) == 0) {

            memcpy(sr, new, newlen);

            sr += newlen;

            s  += oldlen;

        } else

            *sr++ = *s++;

    }

    *sr = '\0';

 

    return ret;

}

 

int main(void)

{

    char mystr[] = "##this is##an examp#le";

    char *newstr = NULL;

 

    puts(mystr);

 

    newstr = replace(mystr, "##", "****");

    if (newstr == NULL)

        puts("replace returned NULL");

    else

        puts(newstr);

 

    free(newstr);

    return 0;

}

----------------------------EOF----------------------------------------------

 

Pradyut
http://pradyut.tk
http://spaces.msn.com/members/oop-edge/
http://groups-beta.google.com/group/oop_programming
India

 

No comments: