strlen函数编写
strlen介绍:
#include <string.h>
size_t strlen(const char *s);
功能:计算字符串实际长度,不包括\0
参数:s:目标字符串首地址
返回值:字符串实际长度
初级写法:
#include <stdio.h>
int Mystrlen(char *s)
{
int num = 0;
while (*s != '\0')
{
num++;
s++;
}
return num;
}
int main(int argc, const char *argv[])
{
printf("%d\n", Mystrlen("helloworld"));
return 0;
}
高级写法:
#include <stdio.h>
size_t strlen(const char *s)
{
const char *sc;
for (sc = s; *sc != '\0'; ++sc)
/* nothing */;
return sc - s;
}
int main(int argc, const char *argv[])
{
printf("%d\n", strlen("helloworld Good"));
return 0;
}
#ifndef __HAVE_ARCH_STRLEN
/**
* strlen - Find the length of a string
* @s: The string to be sized
*/
size_t strlen(const char *s)
{
const char *sc;
for (sc = s; *sc != '\0'; ++sc)
/* nothing */;
return sc - s;
}
EXPORT_SYMBOL(strlen);
#endif
strcpy和strncpy函数编写
简介:
#include <string.h>
char *strcpy(char *dest, const char *src);
功能:实现字符串的复制
参数:dest:目标字符串的地址
src:源字符串的地址
返回值:目标字符串的地址
char *strncpy(char *dest, const char *src, size_t n);
功能:实现字符串的复制
参数:dest:目标字符串的地址
src:源字符串的地址
n:个数
返回值:目标字符串的地址
注意:字符串的结束字符'\0',也会一起拷贝。
初级写法:
#include <stdio.h>
char *Mystrcpy(char *a, char *b)
{
char *p = a;
while (*b != '\0')
{
*a = *b;
a++;
b++;
}
*a = *b;
return p;
}
int main(int argc, char *argv[])
{
char s1[22] = "helloworld";
char s2[22] = "Good";
Mystrcpy(s1, s2);
printf("%s", s1);
printf("\n");
return 0;
}
高级写法:
#include <stdio.h>
char *strcpy(char *dest, const char *src)
{
char *tmp = dest;
while ((*dest++ = *src++) != '\0')
/* nothing */;
return tmp;