1、模拟实现strncpy

(strncpy是将一个字符串的n个字符复制到另一个字符串中,模拟实现strncpy是要注意到字符串的"\0")

#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<stdlib.h>
#pragma warning (disable:4996)
char*my_strncpy(char*dest, const char*src, size_t num)
{
assert(dest != NULL);
assert(src != NULL);
char* ret = dest;
while (num)           
{
*dest++ = *src++;
num--;
}
if (*(dest - 1) != '\0' )     //判断是否已经将‘\0’复制到目标字符串中  
{
*dest = '\0';
}                                    //若没有则给目标字符串最后添加‘\0’   
return ret;
}
int main()
{
char *p = "abcd";
char q[5];
printf("%s\n", my_strncpy(q, p, 2));
system("pause");

return 0;

运行结果:

}长度受限制的字符串模拟函数

2、模拟实现strncat

(strncat--字符串拼接,将* src字符串中n个字符连接到* dest字符串的有效字符的后面,最后还要加上’\0’)

char *my_strncat(char *dest, const char *src, int count)
{
assert(dest);
assert(src);
char *tmp = dest;
while (*dest != '\0')
{
dest++;
}
while ((count--) && (*src))
{
*dest++ = *src++;
}
*dest = '\0';
return tmp;
}
int main()
{
char a[20] = "hello";
char b[] = "hi";
my_strncat(a, b, 5);
printf("%s\n", a);
system("pause");
return 0;

}

运行结果:

长度受限制的字符串模拟函数

3、模拟实现strncmp

(strncmp--字符串比较(指定长度),比较到出现另一个字符不一样或者一个字符串结束或者num个字符全部比较完)

int my_strncmp(char* dest, const char* src, size_t count)
{
assert(dest);
assert(src);
while (count)
{
if (*dest == *src)
{
dest++;
src++;
}
else
{
return *dest - *src - '\0';
}
count--;
}
return 1;
}


int main()
{
char arr1[20] = "hello";
char arr2[] = "world!";
int ret = my_strncmp(arr1, arr2, 2);
if (ret == 1)
{
printf("Success!\n");
}
else
{
printf("Failure!\n");
printf("%d", ret);
}
system("pause");
return 0;
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-14
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2022-12-23
  • 2022-01-10
猜你喜欢
  • 2022-12-23
  • 2021-08-14
  • 2021-05-22
  • 2021-06-03
  • 2021-06-27
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案