天天看点

C语言 trim 函数

实现C语言中用于对字符串的trim处理

#include <string.h>
#include <ctype.h>


void trim(char *s) 
{
    char *start;
    char *end;
    int len = strlen(s);
    
    start = s;
    end = s + len - 1;

    while (1) 
    {   
        char c = *start;
        if (!isspace(c))
            break;

        start++;
        if (start > end)
        {   
            s[0] = '\0';
            return;
        }   
    }   


    while (1) 
    {   
        char c = *end;
        if (!isspace(c))
            break;

        end--;
        if (start > end)
        {   
            s[0] = '\0';
            return;
        }
    }

    memmove(s, start, end - start + 1);
    s[end - start + 1] = '\0';
}
           

继续阅读