-
Count the length of strintg without using strlen?
Is there a way to count the characters in a string without using strlen? I was trying to write my own string length function by using the array....Do
I have to initialize the char array? Can someone
just give me a hint please??? Here are part of the
code I have so far, very very ugly.......I don't
even know what am I doing anymore......
#include <stdio.h>
int length(char[]); /* prototypes the function for the length of the char */
char oddeven(int); /* prototypes the function for even or odd char length */
int main(void)
{
int x;
char array[26];
length(array);
x=length(array);
printf("\nThe length of the string is %d characters\n", x);
return 0;
}
int length(char array[]) /* define the function of char length */
{
int i = 0;
/* char array[26];*/ /* 25 characters + 1 for the \0 */
char c;
printf("\nPlease enter a string, maximum of 25 characters;\n");
c = getchar();
while(c != '\0' && c != '\n')
{
array[i++] = c;
return i;
}
}
-
I change the characters function to:
printf("\nPlease enter a string, maximum of 25 characters;\n");
gets( array );
while(array[i] != '\0' && array[i] != '\n')
{
i++;
return i;
}
Still didn't work it return 1 for the characters length after I type like 13 letters, also it prints out "Please enter a string, maximum of 25 characters" two time. Why????Please help anyone?
thank you...
-
ok I change a few thing again (can you guys see
I'm trying very hard.. ^__^)
but, when I run the program, 1)I type in few characters hit return, nothing happen, like it's wating for something, so I type it in again, this time it took the string...2)but it also count the "Enter" key that was push by the user after the characters was enter. Can some one help me sove this two problems?
thank you......
int length(char[]); /* prototypes the function for the length of the char */
char oddeven(int); /* prototypes the function for even or odd char length */
int main(void)
{
int x;
char array[26];
printf("\nPlease enter a string, maximum of 25 characters:\n"); <--------
length(array);
x=length(array);
printf("\nThe length of the string is %d characters\n", x);
return 0;
}
int length(char array[]) /* define the function of char length */
{
int i = 0; <------
int c = 0; <------
while (c != '\n') <-------
{
array[i++] = c; <-------
c = getchar(); <-------
}
array[i] = '\0'; <-------
return i;
}
-