您的位置:首页 > 其它

自己整理的关于C的一些字符串处理函数

2010-04-24 22:37 387 查看
鉴于在用C语言写一些字符串处理的程序时种种的不便,本人坚信"磨刀不误砍柴功"这个信条,于是在专门

进行了一次磨对C语言的磨刀,写了一些字符串的处理函数, 方便网友使用, 大家有好的解决方法也请告知一下.

    我估计有一些C的库中肯定有比我这更好的函数, 但是本人没有找到, 望"行家"告知.

#include <string.h>
/********************************************************
返回字符ch在head字符串中首次出现的位置
********************************************************/
int indexString(char* head, char ch)
{
int i=0;
int flag=0;
while(head[i]!=0)
{
if(head[i] == ch)
{
flag=1;
break;
}
i++;
}
if(flag)
return i;
else
return -1;
}
/********************************************************
求子字符串的函数:取字符串head中从start位置到end
位置处的字符串,如head="hello world xphag",
subString(head, 0, strlen(head)-1)的结果为"hello world xphag"
subString(head, 0, 0)的结果为"h"
********************************************************/
char* subString(char* head, int start, int end)//取字符串的start位置到end位置的子字符串(含start),失败返回NULL
{
int i=0, j=0;
i=strlen(head);
if(start>=i || end>= i || start> end)
return NULL;
char* p=(char* )malloc(sizeof(char)* (end-start+2));
for(i=start; i<=end; i++ )
p[j++]=head[i];
p[j]=0;
return p;
}
/********************************************************
计算ch字符在字符串head中的出现的次数
********************************************************/
int containString(char* head, char ch)
{
int i=0, count=0;
while(head[i]!=0)
{
if(head[i]==ch)
count++;
i++;
}
return count;
}
/*********************************************************
字符串分割函数,将head字符串从ch处分开,
如: hello world xphag, 从' '分开后为
hello, world, xphag三个字符串
*********************************************************/
char** seperateString(char* head, char ch)
{
int i=containString(head, ch);
int j=0, k;
char* p=subString(head, 0, strlen(head)-1), *q;
if(i==0)
return NULL;
char** result=(char**)malloc((i+1)*sizeof(char*));
for(j=0; j<i; j++)
{
k=indexString(p, ' ');
q=subString(p, 0, k-1);
result[j]=q;
q=subString(p, k+1, strlen(p)-1);
delete(p);
p=q;
}
result[j]=p;
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: