开发者

Write a function int mystrlen(char *s) that returns the number of characters in a string wuthout strlen func [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. 开发者_开发知识库 Closed 9 years ago.

heres what i did, i just have ne error that i cant figure out.

int mystrlen(char string[])
{
 char string1[LENGHT], string2[LENGHT];
 int len1, len2;
 char newstring[LENGHT*2];

 printf("enter first string:\n");
 len1 = mystrlen(string1);
 printf("enter second string:\n");
 len2 = mystrlen(string2);

 if(len1 == EOF || len2 == EOF)
  exit(1);

 strcpy(newstring, string1);
 strcat(newstring, string2);

 printf("%s\n", newstring);

 return 0;


Cheating, but follows your rules...

int mystrlen( char *s)
{
    return strchr( s, '\0') - s;
}


You recursively call the same function on all branches. It ain't gonna work - the program will incur stack overflow and most likely crash big time.

You need to structure the program somehow like this:

int mystrlen(char string[])
{
    //compute length here
}

void testStuff()
{
    //your code here
}


Try to read your program using Pseudocode - It will probably be easier to understand then :)

  1. Declare variables string1, string2, len1, len2, newstring
  2. Print a message
  3. 3 Go to 1
    3.1. Declare variables string1, string2, len1, len2, newstring
    3.2. Print a message
    3.3. Go to 3.1
    ... 3.3.1 Declare variables string1, string2, len1, len2, newstring
    ... 3.3.2 .....

You see the error? :)


To come up with a solution to your problem, you must understand that in C a "string" is an array of characters terminated by '\0'. That should be enough to help you work through a proper solution.


int mystrlen(char string[])
{
    int i = 0;
    while(string[i] != '\0'){
        ++i;
    }
    return i;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜