您的位置:首页 > 编程语言 > C语言/C++

C语言字符串操作函数实现

2015-03-30 00:16 399 查看
1、字符串反转–strRev

voidstrRev(char*str)
{
assert(NULL!=str);
intlength=strlen(str);
char*end=str+length-1;

while(end>str)
{
*str=(*str)^(*end);
*end=(*str)^(*end);
*str=(*str)^(*end);

end--;
str++;
}
}


2、字符串复制–strcpy

char*strcpy(char*strDest,constchar*strStr)
{
assert((NULL!=strDest)&&(NULL!=strStr));

char*Dest=strDest;

while((*Dest++)=(*strStr++))
{}

returnstrDest;
}


3、字符串拼接–strcat

char*strcat(char*strDest,constchar*strStr)
{
assert((NULL!=strDest)&&(NULL!=strStr));

intlength=strlen(strDest);

char*Dest=strDest+length;

while((*Dest++)=(*strStr++))
{}

returnstrDest;
}


4、字符串比较–strcmp

intstrcmp(constchar*strDest,constchar*strStr)
{
assert((NULL!=strDest)&&(NULL!=strStr));

while(0==(*strDest-*strStr)&&*strDest)
{
strDest++;
strStr++;
}

if(*strDest>*strStr)
return1;
elseif(*strDest<*strStr)
return-1;
else
return0;
}


5、字符串长度–strlen

intstrlen(constchar*strStr)
{
assert(NULL!=strStr);

intlength=0;

while('\0'!=*strStr)
{
length++;
strStr++;
}

returnlength;
}


6、字符串转数字–atoi

intatoi(constchar*strStr)
{
assert(NULL!=strStr);

intminus=0;
intbegin=0;
intsum=0;

while('\0'!=*strStr)
{
if(0==begin&&(isdigit(*strStr)||'+'==*strStr||'-'==*strStr))
{
begin=1;

if('-'==*strStr)
{
minus=1;
strStr++;
continue;
}
}
elseif(!isdigit(*strStr))
{
printf("formatiswrong!\n");
exit(1);
}

if(1==begin)
{
sum=sum*10+(*strStr-'0');
}

strStr++;
}

returnminus?(-sum):(sum);
}


7、数字转字符串–atoi

char*itoa(intnum)
{
inttemp,i,j;
chararray[10];
staticcharstrDest[10];

for(temp=num,i=0;i<10&&temp;i++)
{
array[i]=temp%10+'0';
temp/=10;
}

for(i=i-1,j=0;i>=0&&j<10;i--,j++)
{
strDest[j]=array[i];
}
strDest[j]='\0';

returnstrDest;
}


8、计算字符串中元音字符的个数

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<ctype.h>

intisVowel(charletter)
{
switch(toupper(letter))
{
case'A':
case'E':
case'I':
case'O':
case'U':
return1;
default:
return0;
}
}

intcountVowel(constchar*strStr)
{
assert(NULL!=strStr);

intcount=0;

while('\0'!=*strStr++)
{
if(isVowel(*strStr))
count++;
}

returncount;
}

intmain()
{
chara[10]="hwlulr";

printf("%d\n",countVowel(a));

return0;
}


9、判断一个字符串是否是回文

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<ctype.h>

intisEqual(chara,charb)
{
if(a==b)
return1;

return0;
}

intisPalindrome(constchar*strStr)
{
assert(NULL!=strStr);

intlength=strlen(strStr);
inti,j;

for(i=0,j=length-1;i<j;i++,j--)
{
/*跳过空格和符号*/
while(''==*(strStr+i)||!isalpha(*(strStr+i)))
i++;
while(''==*(strStr+j)||!isalpha(*(strStr+j)))
j--;

if(0==isEqual(*(strStr+i),*(strStr+j)))
return0;
}

return1;
}

intmain()
{
chara[10]="heoo,eh";

printf("%s\n",isPalindrome(a)?"isPalindrome":"isnotPalindrome");

return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: