我使用this question爲導向,以修整一個串C.它上正常工作完全由空格(' '
)爲界的字符串,但在特殊的空格('\r'
,'\n'
,'\t'
等修剪字符串), 它失敗。這裏有一個例子:麻煩在C
#include <stdio.h>
#include <string.h>
size_t trim(char *out, size_t len, const char *str)
{
if(len == 0)
return 0;
const char *end;
size_t out_size;
// Trim leading space
while(isspace(*str)) str++;
if(*str == 0) // All spaces?
{
*out = 0;
return 1;
}
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace(*end)) end--;
end++;
// Set output size to minimum of trimmed string length and buffer size minus 1
out_size = (end - str) < len-1 ? (end - str) : len-1;
// Copy trimmed string and add null terminator
memcpy(out, str, out_size);
out[out_size] = 0;
return out_size;
}
int main(){
char *str = " \n\n hello \t \r ";
char trimmed[strlen(str)];
trim (trimmed, strlen(trimmed), str);
printf("~%s~\n~%s~\n", str, trimmed);
return 0;
}
產生輸出:
~
~ello
~~
任何人都可以修改代碼以正確修剪所有空格字符?
第二個問題:引用答案中的第一個函數給了我一個段錯誤。有誰知道這是爲什麼?
誰**下**投票後有一點ç知識或耐心閱讀代碼的人,他應該已經注意到,所有三個函數僅適用於空格(ASCII碼32位十進制),不適用於\ r,\ n或\ t!這只是修改if條件的問題,或者更好的方法可能是更新函數原型以接受所需的空格字符來移除,如char * zstring_trim(char * str,const char space)。 – 2016-04-03 23:25:29