ch5-strlen (String length), pointer version

Chapter_5     Exercise_5-2     pointers strcpy     Exercise_5-3







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
*/





Note:  See also strlen in Chapter_2.









Chapter_5     Exercise_5-2     pointers BACK_TO_TOP strcpy     Exercise_5-3



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo