c语言操作字符串相关

现在IT行业笔试题大部分都有操作字符串相关的,尤其是微软特别注重基本的字符串操作,空闲时间整理了一些,以备以后用。

1.模拟实现strcpy函数

char *strcpy(char *dst, const char *src)
{
assert((dst != NULL) && (src != NULL));
char *tmp = dst;
while ((*dst++ = *src++) != '\0')
{
/* nothing */;
}
return tmp;
}

2.模拟实现strlen函数

int strlen( const char *str )
{
 assert( str != NULL );
 int len;
 while( (*str++) != '\0' )
 {
  len++;
 }
 return len;
}

3.模拟实现strcmp函数

int strcmp(char *source, char *dest)
{
assert((source!= NULL) && (dest!= NULL));
while(*source++ == *dest++)
{
if(*source =='\0' && *dest=='\0')
return 0;
}

return -1;

}

4.模拟实现strcat函数

char* strcat ( char * dst , const char * src )
{
char * cp = dst;
while( *cp )
cp++;
while( *cp++ = *src++ ) ;
return( dst );
}

5.判断字符串是否含有回文

/*
* 程序功能:判断一个单词,或不含空格、标点符号的短语是否为回文(palindrome)
*/
#include <stdio.h>
#include <ctype.h>

int is_palindrome(const char *s)
{
bool is_palindrome=0;
const char *end=s;

if(*end == '\0') /* 如果s为空串,则是回文 */
is_palindrome=1;

while(*end) ++end; /* end指向串s最后一个字符位置 */
--end;

while(s<=end)
{
while(*s==' ' || !isalpha(*s)) /* 略去串s中的非字母字符 */
++s;
while(*end==' ' || !isalpha(*end))
--end;
if(toupper(*s) == toupper(*end)) /* 将s中的字母字符转换为大字进行判断 */
{
++s;
--end;
}
else
{
is_palindrome=0; break;
} /* 在s<=end的条件下,只要出现不相等就判断s不是回文 */
}
if(s>end)
is_palindrome=1;
else
is_palindrome=0;
return (is_palindrome);

}

int main()
{
const char *s ="Madam I' m Adam";
printf("%s %s \n", s, is_palindrome(s) ? "is a palindrome!": "is not a palindrome!");
return 0;
}

6.反转字符串

void strRev(char *s)
{
char temp, *end = s + strlen(s) - 1;
while( end > s)
{
temp = *s;
*s = *end;
*end = temp;
--end;
++s;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值