[英]Creating an strlen function in c
the mission is to create a function that replaces strlen but in the order I'll present you'd have to fill the empty spots.任务是创建一个 function 来替换 strlen 但按照我要介绍的顺序,你必须填补空白。 I tried something but got stuck where I need to count the size and return it.我尝试了一些东西,但卡在了我需要计算尺寸并将其退回的地方。
#include <stdio.h>
#define MAXLENGTH 80
int my_strlen(char* s)
{
char *p = (1);
while (2)
(3);
return (4);
}
int main()
{
char str[MAXLENGTH];
int len;
printf("Enter a string:");
gets(str);
len = my_strlen(str);
printf("The length of the string %s is %d\n", str, len);
}
I tried this but got stuck at 3, how to count the size我试过这个但卡在3,如何计算大小
#include <stdio.h>
#define MAXLENGTH 80
int my_strlen(char* s)
{
char *p = s;
while (*p++ != '\0')
(3);
return (4);
}
int main()
{
char str[MAXLENGTH];
int len;
printf("Enter a string:");
gets(str);
len = my_strlen(str);
printf("The length of the string %s is %d\n", str, len);
}
size_t mystrlen(const char *restrict s)
{
const char *restrict e = s;
while(*e) e++;
return (uintptr_t)e - (uintptr_t)s;
}
But I would not advice to show it your teacher.....但我不建议向你的老师展示......
I've just replaced your (3)
and (4)
with i++
that will increment until termination (\0) and will return (i)
.我刚刚用i++
替换了你的(3)
和(4)
,这将增加直到终止(\0)并返回(i)
。
#include <stdio.h>
#define MAXLENGTH 80
int my_strlen(char* s)
{
int i=1;
char *p = s;
while (*p++)
i++;
return (i);
}
int main()
{
char str[MAXLENGTH];
int len;
printf("Enter a string:");
gets(str);
len = my_strlen(str);
printf("The length of the string %s is %d\n", str, len);
}
returning value will be +1 (including \0)返回值为+1 (包括\0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.