Remove characters from a string in C

后端 未结 4 1137
生来不讨喜
生来不讨喜 2020-12-10 08:34

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.

相关标签:
4条回答
  • 2020-12-10 08:55
    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;
    
    0 讨论(0)
  • 2020-12-10 08:58

    Allocate another buffer, either on the stack or the heap, and then copy the string into the new buffer 1 character at a time. Make special handling when you encounter the & character.

    0 讨论(0)
  • 2020-12-10 09:00

    Basically, you need to:

    • use the strstr() function to find the "&"s
    • copy characters to the resulting buffer up to the position found
    • skip 4 characters
    • repeat until NUL
    0 讨论(0)
  • 2020-12-10 09:12

    C isn't noted for it's ease of use, especially when it comes to strings, but it has some rather nice standard library functions that will get the job done. If you need to work extensively on strings you'll probably need to know about pointers and pointer arithmetic, but otherwise here are some library functions that will undoubtedly help you:

    • strchr() to find a character (say, '&') in a string.
    • strcmp() and strncmp() to compare two strings.
    • strstr() to find a substring in a string (probably easier and faster than using the strchr()/strcmp() combination).
    • malloc() to allocate a new string.
    0 讨论(0)
提交回复
热议问题