c语⾔strtrim函数⽤法,C语⾔字符串⼯具箱DIY之剔除字符串⾸
尾的空⽩字符的str_。。。
@Header File Named "string_toolbox.h"
Contents of File "string_toolbox.h"
Are as follows:
#ifndef STRING_TOOLBOX_H_INCLUDED
#define STRING_TOOLBOX_H_INCLUDED
char *str_trim(const char *str);
#endif
@Source File Named "string_toolbox.c"
Contents of File "string_toolbox.c"
Are as follows:
#include "string_toolbox.h"
#include
#include
#include
char *str_trim(const char *str)
{
size_t
i = 0,
j = strlen(str),
k = 0,
new_lenth;
while(isspace(str[i])){
++i;
}
if(i == j) return "";
while(isspace(str[--j]));
new_lenth = j - i + 1;
char *result =(char *)
malloc(new_lenth + 1);
while(k < new_lenth){
result[k++] = str[i++];
}
result[k] = '\0';
returnresult;
}
@Source File  for Testing Named "main.c"
Contents of File "main.c"
Are as follows:
#include "string_toolbox.h"
#include
#include
#define STR_CAT3(d, s1, s2, s3)(strcat(strcat(strcat(d, s1), s2), s3)) intmain()
{
char
*str1 = "1",
*str3 = "3",
*str2[4] = {
" \t 2\t2 \n \v \t ", // 12  23
" \t 22 \n \v \t ", // 1223
" \t 2 \n \v \t ", // 123
" \t \n \v \t " // 13
};
inti = 0;
while(i < 4){
chardest_buf[8] = {'\0'};
printf("%s\n",
STR_CAT3(dest_buf,
str1,
str_trim(*(str2+i)),
str3)
);
++i;
}
printf("%d\n", isspace('\0')); // 0
return0;
}
Postscripts
(1)size_tis type_alias of "unsigned int".
c++string类型
(2)Function void *malloc(size_t n_bytes); is declared in .
It is used to dynamically allocate memory.
(3) Functionsize_tstrlen(const char *str);is declared in.
It counts how many valid charaters(that is the amount of charaters before'\0') are in this string.
(4) Function char *strcat(char *destination_string_buf, const char *source_string); is  declared in .
It appends the source_string to the ending of the destination_string_buf on '\0'. The destination_string_buf should contain a C string, and be large enough to contain the concatenated resulting string.
(5)Function intisspace(intc); is declared in .
It checks whether c is a white-space character.For the "C" locale, white-space characters are any of :
' '
(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)
(5)Details of Indexed Comments (Like @Comment_N) Above
原字符串全部可访问的下标范围为闭区间[0, strlen(str)];
printf("%d\n", isspace('\0'));会输出0, 即'\0'不被作为空⽩字符;
满是空⽩字符,精简后即是空字符串咯;
因为isspace('\0')为假, 因此应直接从'\0'的前⼀个字符开始检测空⽩;
精简后得到的新字符串全部可访问的下标范围为闭区间[0, new_lenth];
Copyright NOT Fully Reserved © yawenunion@whatever On 20180403

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。