/****************
* 函數原型:
* int ltrim_str(char* str, const char* filter);
* int rtrim_str(char* str, const char* filter);
* int trim_str(char *str, const char *filter);
* int ltrim_ch(char* str, char ch);
* int rtrim_ch(char* str, char ch);
* int trim_ch(char *str, char ch);
* ltrim表示去左,rtrim表示去右,trim表示左右都去,filter字符串可以同時指定多個字符
* 功能描述:在str的開頭(或結尾)過濾掉指定字符,第二個參數指定這些字符
* 輸入參數:字符串str和一個字符(串)
* 輸出參數:過濾後的str
* 返回值:成功返回被過濾掉的字符總數,失敗(如傳入NULL參數)返回NULL
*********************/
#include <stdio.h>
#include <string.h>
int ltrim_str(char* str, const char* filter)
{
char* ptr = str;
if (str == NULL || filter == NULL)
{
return -1;
}
for(; *ptr; ++ptr)
{
if(!strchr(filter, *ptr)) break;
}
strcpy(str, ptr);
return ptr-str;
}
int ltrim_ch(char* str, char ch)
{
char* ptr = str;
if (str == NULL)
{
return -1;
}
for(; *ptr; ++ptr)
{
if(*ptr != ch) break;
}
strcpy(str, ptr);
return ptr-str;
}
int rtrim_str(char* str, const char* filter)
{
int i;
int len = strlen(str);
if (str == NULL || filter == NULL)
{
return -1;
}
for (i = len - 1; i >= 0; i--)
{
if(!strchr(filter, str[i])) break;
}
str[i+1] = '\0';
return len-i-1;
}
int rtrim_ch(char* str, char ch)
{
int i;
int len = strlen(str);
if (str == NULL)
{
return -1;
}
for (i = len - 1; i >= 0; i--)
{
if(str[i] != ch) break;
}
str[i+1] = '\0';
return len-i-1;
}
int trim_str(char *str, const char *filter)
{
if (str == NULL || filter == NULL)
{
return -1;
}
return ltrim_str(str, filter) + rtrim_str(str, filter);
}
int trim_ch(char *str, char ch)
{
if (str == NULL)
{
return -1;
}
return ltrim_ch(str, ch) + rtrim_ch(str, ch);
}
int main()
{
int n=0;
char str1[20]=" 111abcde*+*+";
char str2[20]=" 111abcde*+*+";
puts(str1);
n += ltrim_str(str1, "1 ");
puts(str1);
n += rtrim_str(str1, "*+");
puts(str1);
printf("%d\n", n);
n = trim_str(str2, "*+1 ");
puts(str2);
printf("%d\n", n);
return 0;
}