-
Notifications
You must be signed in to change notification settings - Fork 0
/
strlen.c
45 lines (35 loc) · 989 Bytes
/
strlen.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <stdio.h>
#include <string.h>
size_t stringlen(const char *s);
int read_line(char str[], int n);
size_t fast(const char *s);
#define MAX_LENGTH 255
int main(void){
char msg_str[MAX_LENGTH + 1];
printf("Enter a string to determine it's length: ");
read_line(msg_str, MAX_LENGTH);
printf("The length of the string is: %zu\n", stringlen(msg_str));
}
/* faster version. Doesn't increment n */
size_t fast(const char *s){
const cahr *p = s;
while(*s)
s++;
return s - p;
}
size_t stringlen(const char *s){
size_t n;
for (n = 0; *s != '\0'; s++) // Iterates until the pointer is a null value.
n++;
return n;
}
/* Iterates through the char array and pushes the char at the index into str[],
* breaks when it encounters a null value in the string. */
int read_line(char str[], int n){
int ch, i = 0;
while ((ch = getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}