Click here to Skip to main content
15,883,127 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I compute length of the string with strlen() function and function have to return the number of characters in c?

What I have tried:

#include <stdio.h>
#include <string.h>

int my_strlen(char* param_1)
{
int i;
for(i = 0; i < ¶m_1; param_1++){
printf("%d", i);
}
return 0;
}

or
i had to count length of param_1
Posted
Updated 2-Aug-22 4:43am
Comments
Richard MacCutchan 2-Aug-22 9:58am    
Count all the characters until you reach a null byte.

1 solution

The C language does not have a string type: it represents them via an array of chars, with a "special character" at the end which is a null value: '\0'

This combines well with the lack of a boolean type, in that any non-zero value is true and a zero (or null) being false.
So it is pretty easy to identify the end of a "string" in a loop:
C
for (int i = 0; param_1[i]; i++) {}
You could use the pointer version instead of an array index, but that would require two increments instead of one.

You also need to fix the loop body, and return a value from the function if you want decent code.

I'd also recommend that the parameter should be a const char* instead of a char * :
C
#include <stdio.h>
int my_strlen(char* param_1)
    {
    int i;
    for (i = 0; param_1[i]; i++)
       {
       }
    return i;
    }
int main()
    {   
    const char* str = "hello world";
    printf("%s:%u\n", str, my_strlen(str));
    return 0;
    }
 
Share this answer
 
Comments
gggustafson 2-Aug-22 11:33am    
I thought we weren't giving away our secrets completely.
OriginalGriff 2-Aug-22 12:04pm    
He was getting close, and it was such a trivial problem that it's pretty much impossible to guide him without complete code.
But ... it's not something he can hand in without changes as it's more advanced than his course has got yet I suspect ... :D
gggustafson 2-Aug-22 12:11pm    
OK
Irodabonu Komilova 3-Jan-23 6:43am    
thank you
OriginalGriff 3-Jan-23 6:58am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900