trim,ltrim,rtrim自定义实现
#include <stdio.h>
#include <memory.h>
#include <ctype.h>
#include <stdlib.h>
char *_trim(const char *str, int left, int right) {
size_t size = strlen(str);
char *preptr = str;
char *posptr = str + size - 1;
if (preptr && left) {
while (isspace(*(preptr))) {
preptr++;
}
}
if (posptr && right) {
while (isspace(*(posptr))) {
posptr--;
}
}
char *newstr = malloc(posptr - preptr);
char *newstrptr = newstr;
while (preptr <= posptr) {
*(newstrptr++) = *(preptr++);
}
// 设置字符串结束符,malloc分配的内存空间,没有进行初始化,如果没有该操作,可能会出现莫名其妙的问题
*(newstrptr) = '\0';
return newstr;
}
char *rtrim(const char *str) {
return _trim(str, 0, 1);
}
char *ltrim(const char *str) {
return _trim(str, 1, 0);
}
char *trim(const char *str) {
return _trim(str, 1, 1);
}
int main() {
char *str = " hellow, world ";
char *newstr = rtrim(str);
printf("%s\n", newstr);
free(newstr);
newstr = ltrim(str);
printf("%s\n", newstr);
free(newstr);
newstr = trim(str);
printf("%s\n", newstr);
free(newstr);
return 0;
}
结果:
hellow, world
hellow, world
hellow, world