前言
看到很多使用迭代起吊空字符的,覺得代發寫的太費勁。這裏提供一段使用strspn實現的代碼
簡單介紹strspn
strspn位於string.h,姊妹函數strcspn和strtok
函數聲明:size_t strspn(const char *str1, const char *str2);
此函數用於從str1總找到不包含在str2中的任何字符,並返回index。
具體的介紹可自行搜索,也可參考c plus plus函數介紹。
廢話不多說,直接上代碼。這裏假定空白字符包含:空格,\r,\n,\r,\v,\f這6個字符。
#include <string.h>
#include <stdint.h>
char* trim(char* objStr){
uint32_t idx;
idx = strspn(objStr, " \r\n\t\v\f");
return (objStr+idx);
}
/*這裏可以測試一下*/
int main(void){
char test[] = "\r\n\t It is a long long ago...\r\n";
printf("original:\r\n%s", test);
printf("trimed:\r\n%s", trim(test));
}
測試結果如下:
original:
It is a long long ago...
trimed:
It is a long long ago...
結論
這篇文章很短,代碼更短。但是基本科技解決去掉開頭空白字符的問題。
但是怎麼去掉結尾空白字符吶?或者怎麼去掉中間的空白字符吶?
開動你的小腦筋吧…