字符串的一些操作函数

来源:互联网 发布:水果网络批发市场 编辑:程序博客网 时间:2024/06/04 23:21

字符串反转

charstr_rev(char *str, size_t len)

{

char*start = str;指向字符数组头

char*end = str+len-1;指向字符数组尾

charch;

 

if(str!= NULL)

{

while(start< end)

{交换尾部和头部的字符,并同时移动头部和尾部指针

ch= *start;

*start++= *end;

*end--= ch;

}

}

returnstr;

}

去掉指定字符

void removeStr(char *str,char *re)
{
int a[26]={0},i=0,j=0;
while(re[i]!='\0')
{
a[re[i]-'a']=1;
i++;
}
i=0;
while(str[i]!='\0')
{
if(a[str[i]-'a']==0)
{
str[j++]=str[i];
}
i++;
}
str[j]='\0';
}

反转单词的操作函数

void reverseWords(char *str)
{
int len,i,j,k;
char *copyStr=NULL,*temp=NULL;
len=strlen(str);
    copyStr=(char*)malloc(len+1);
assert(copyStr!=NULL);
temp=copyStr;
k=0;
    for(i=len-1;i>=0;i--)
{
k++;
if(str[i]==' ')
{
j=i;
while(k>1)
{
   *copyStr++=str[++j];
k--;
}
k=0;
*copyStr++=' ';
}
if(i==0)
{
j=i;
while(k>0)
{
   *copyStr++=str[j++];
k--;
}
*copyStr='\0';
}
}
strcpy(str,temp);
free(temp);
copyStr=NULL;
temp=NULL;
}

0 0
原创粉丝点击