面-试-题

字符串

警告

if(strlen(a)>=strlen(b)){};√对
if(strlen(a)>=strlen(b)){};×错
因为strlen的返回值是无符号的

1.用一条语句实现strlen();

1.递归思想,Mystrlen(s) = Mystrlen(s+1) + 1;
2.逗号表达式的返回值取决于后一个,也就是前一个对结果无影响

#include <stdio.h>
#include <assert.h>
unsigned int Mystrlen(const char* s)
{
  return ((assert(s)),(*s ? (Mystrlen(s+1) + 1) : 0));
}
int main(void)
{
  printf("%d\n",Mystrlen("123"));
}
//自己第一次写的,能实现功能但是有两个缺点
#include <stdio.h>
#include<stdlib.h>
unsigned int Mystrlen(char* string)//1.应该防止这个字符串被修改所以应该改为const char *string
{
   unsigned int ret = 0;
   if(string != NULL)     
   {
      while(string[ret]!='\0')//2.用数组访问效率低于指针详见
      {
        ret++; 
      }
   }
   return ret;
 }
 int main(void)
 {
    char *a = "hello";  
    printf("%d\n",Mystrlen(a));
    return 1;
 } 

编写函数实现strcpy();

//自己的实现,有三点不足
//1、没有传入的实参进行检查assert(dest&&soure)
//2、程序有点冗余,
#include <stdio.h>
#include <assert.h>
char* Mystrcopy(char* dest,const char* source)
{
  char *ret = NULL;
  ret = dest;
  while(*source++ != '\0')//先判断后赋值导致程序冗余
  {
    *dest++ = *source++;
  }
  *(++dest) = '\0';//冗余
  return ret;
}
int main()
{
  char dest[10] = {0,1,2,3,4,5,6,7};
  char source[] = "hello";
  printf("%s\n",Mystrcopy(dest,source));
  return 1;
}

正解

#include <stdio.h>
#include <assert.h>
char* Mystrcopy(char* dest,const char* source)
{
  char *ret = dest;
  assert(dest&&source);//安全性检查
  while((*dest++ = *source++)!= '\0');先赋值后判断
  return ret;
}
int main()
{
  char dest[10] = {0,1,2,3,4,5,6,7};
  char source[] = "hello";
  printf("%s\n",Mystrcopy(dest,source));
  return 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WAF001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值