C语言实现去除字符串首尾空格
程序员文章站
2023-11-18 10:54:16
/* C语言去除字符串首尾空格,trim()函数实现 https://blog.csdn.net/u013022032/article/details/50521465 */ #include #include #include #in... ......
/* c语言去除字符串首尾空格,trim()函数实现 https://blog.csdn.net/u013022032/article/details/50521465 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> //去除尾部空白字符 包括\t \n \r /* 标准的空白字符包括: ' ' (0x20) space (spc) 空格符 '\t' (0x09) horizontal tab (tab) 水平制表符 '\n' (0x0a) newline (lf) 换行符 '\v' (0x0b) vertical tab (vt) 垂直制表符 '\f' (0x0c) feed (ff) 换页符 '\r' (0x0d) carriage return (cr) 回车符 //windows \r\n linux \n mac \r */ char *rtrim(char *str) { if (str == null || *str == '\0') { return str; } int len = strlen(str); char *p = str + len - 1; while (p >= str && isspace(*p)) { *p = '\0'; --p; } return str; } //去除首部空格 char *ltrim(char *str) { if (str == null || *str == '\0') { return str; } int len = 0; char *p = str; while (*p != '\0' && isspace(*p)) { ++p; ++len; } memmove(str, p, strlen(str) - len + 1); return str; } //去除首尾空格 char *trim(char *str) { str = rtrim(str); str = ltrim(str); return str; } void demo() { char str[] = " ab c \r \n \t"; printf("before trim:%s\n", str); char *p = trim(str); printf("after trim:%s\n", p); } int main(int argc, char **argv) { demo(); return 0; }
上一篇: 杭州成全国首个可凭支付宝健康码看病的城市