大多数语言都有个操作字符串的函数trim。可是c语言的glibc 库里面没带,那就自己DIY个吧。
trim函数的作用是去除字符串两边的空格。
TODO:画图说明
实现源码:
char *ho_trim(char *s) { char *start, *last, *bk; int len; start = s; while (isspace(*start)) start++; bk = last = s + strlen(s) - 1; while (last > start && isspace(*last)) last--; if ((s != start) || (bk != last)) { len = last - start + 1; strncpy(s, start, len); s[len] = '\0'; } return s;}
测试代码:
int main() { char buf[128]; strcpy(buf, " 1234 "); printf("$%s:\n", ho_trim(buf)); strcpy(buf, "1234 "); printf("$%s:\n", ho_trim(buf)); strcpy(buf, " 1234"); printf("$%s:\n", ho_trim(buf)); strcpy(buf, " 1234 abcd "); printf("$%s:\n", ho_trim(buf)); strcpy(buf, " "); printf("$%s:\n", ho_trim(buf)); strcpy(buf, " "); printf("$%s:\n", ho_trim(buf)); return 0;}