吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → 为 strcat() 和 strcmp() 编写一行函数

为 strcat() 和 strcmp() 编写一行函数

来源:网络 | 更新时间:2022-01-13 07:20:34
递归可用于在一行中完成这两项任务。下面是 stracat() 和 strcmp() 的一行实现。
/* my_strcat(dest, src) copies data of src to dest. To do so, it first reaches end of the string dest using recursive calls my_strcat(++dest, src). Once end of dest is reached, data is copied using 
(*dest++ = *src++)? my_strcat(dest, src). */
void my_strcat(char *dest, char *src)
{
(*dest)? my_strcat(++dest, src): (*dest++ = *src++)? my_strcat(dest, src): 0 ;
}

/* driver function to test above function */
int main()
{
char dest[100] = "geeksfor";
char *src = "geeks";
my_strcat(dest, src);
printf(" %s ", dest);
getchar();
} 
与 my_strcmp() 相比,函数 my_strcmp() 更简单。
/* my_strcmp(a, b) returns 0 if strings a and b are same, otherwise 1. It recursively increases a and b pointers. At any point if *a is not equal to *b then 1 is returned. If we reach end of both strings at the same time then 0 is returned. */
int my_strcmp(char *a, char *b)
{
return (*a == *b && *b == '')? 0 : (*a == *b)? my_strcmp(++a, ++b): 1;
} 

/* driver function to test above function */
int main()
{
char *a = "geeksforgeeks";
char *b = "geeksforgeeks";
if(my_strcmp(a, b) == 0)
printf(" String are same ");
else 
printf(" String are not same "); 

getchar();
return 0;
} 
上面的函数做了非常基本的字符串连接和字符串比较。这些函数不提供与标准库函数相同的功能。

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com