/*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; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/71561.html
標籤:C
上一篇:for回圈中的switch的break和continue作用范圍
下一篇:行程調度, 一個調度器的自白
