carraysreplacechar

Remove characters from a string in C


I only have access to 'C' and need to replace characters within a character array. I have not come up with any clean solutions for this relatively simple procedure.

I pass in a character array, for example:

char strBuffer[] = "/html/scorm12/course/course_index.jsp?user_id=100000232&course_id=100000879&course_prefix=ACQ&version=2&scorm_version=3&roster_id=100011365&course_name=Test%20Course%201.2&mode=browse&course_number=0000&mode_id=1";

I need to modify this buffer to replace all the & with &. The resulting buffer does not have to overwrite strBuffer (a new buffer can be created).

Any suggestions?

Edit:

In the past I have used the strstr() function in a loop, but was looking for a simpler solution, perhaps the C equivalent to the String.Replace() method.

Edit:

For my immediate needs, the following is all that I need.

char strBuffer[] = "/html/scorm12/course/course_index.jsp?user_id=100000232&course_id=100000879&course_prefix=ACQ&version=2&scorm_version=3&roster_id=100011365&course_name=Test%20Course%201.2&mode=browse&course_number=0000&mode_id=1";
char strTemp[1024];
char *s = (char*)strBuffer;
int i=0;

while (*s)
{
    strTemp[i++] = *s;
    if (strncmp(s,"&",5) == 0)
    {
        s += 5;
    }
    else
        s++;
}
strTemp[i] = 0;

Future modifications:

EDIT:

I created a blog post to detail the steps and provide a more flexible solution:

http://www.solutionmaniacs.com/blog/2012/11/25/c-removereplace-characters-in-a-string.html


Solution

  • char *s = (char*)strBuffer;
    char sClean[strlen(strBuffer) + 1]; /* +1 for null-byte */
    /* if above does not work in your compiler, use:
        char *sClean = (char*)malloc(sizeof(strBuffer) + 1);
    */
    int i=0;
    while (*s)
    {
        sClean[i++]= *s;
        if ((*s == '&') && (!strncmp(s, "&", 5)) s += 5;
        else s++;
    }
    sClean[i] = 0;