strlen.c
K&R, p. 39, 99, 103
download
#include <stdio.h> // for printf(), scanf()
#define LENGTH 100 // max word length
int strlen1(char*);
int strlen2(char*);
int strlen3(char*);
int main()
{
char word[LENGTH];
printf("Type a word: ");
scanf("%s", word);
printf("strlen1(%s) = %d\n", word, strlen1(word));
printf("strlen2(%s) = %d\n", word, strlen2(word));
printf("strlen3(%s) = %d\n", word, strlen3(word));
return 0;
}
int strlen1(char *s) // returns the length of string s
{
int i = 0;
while (s[i] != '\0')
{
i++;
}
return i;
}
int strlen2(char *s) // returns the length of string s
{
int i = 0;
while (*s++ != '\0')
{
i++;
}
return i;
}
int strlen3(char *s) // returns the length of string s
{
char *p = s;
while (*p) // while (*p != '\0')
{p++;}
return p-s;
}
/*
gcc strlen.c -o strlen
./strlen
Type a word: abracadabra
strlen1(abracadabra) = 11
strlen2(abracadabra) = 11
strlen3(abracadabra) = 11
*/
Comments
Post a Comment