Reputation: 1072
int strlength(const char *myStr){
//variable used for str length counter
int strlength = 0;
//loop through string until end is reached. Each iteration adds one to the string length
while (myStr[strlength] != '\0'){
putchar(myStr[strlength]);
strlength++;
}
return strlength;
}
Why will this not work as intended? I just want to find the length of a string.
Upvotes: 1
Views: 397
Reputation: 6684
No need to worry about fgets() and removing the trailing \n
.
while (myStr[strlength] != '\0'){
putchar(myStr[strlength]);
strlength++; //When mysStr[strlength] == \0, this line would have already incremented by 1
}
Quick fix:
return (strlength-1);//This will return correct value.
A more better approach:
int strlen(const char *s)
{
char *str=s;
while(*str)
{
str++;
}
return (s-str);
}
Upvotes: 0
Reputation: 183978
From a comment on another answer:
I am using fgets to read in a string. and i have checked to make sure that the string that was typed was stored correclty
In that case, there is a trailing newline stored, so your function computes
strlength("hello\n")
The code is correct, you just didn't pass it the input you believed to pass.
Upvotes: 4
Reputation: 16728
More reliable version:
size_t strlength(const char * myStr)
{
return strlen(myStr);
}
Upvotes: 3
Reputation: 172598
You can try this also:-
int string_length(char *s)
{
int c = 0;
while(*(s+c))
c++;
return c;
}
Upvotes: 2