C Programming - Strings - Discussion

Discussion Forum : Strings - General Questions (Q.No. 7)
7.
Which of the following function is correct that finds the length of a string?
int xstrlen(char *s)
{
    int length=0;
    while(*s!='\0')
    {    length++; s++; }
    return (length);
}
int xstrlen(char s)
{
    int length=0;
    while(*s!='\0')
        length++; s++;
    return (length);
}
int xstrlen(char *s)
{
    int length=0;
    while(*s!='\0')
        length++;
    return (length);
}
int xstrlen(char *s)
{
    int length=0;
    while(*s!='\0')
        s++;
    return (length);
}
Answer: Option
Explanation:

Option A is the correct function to find the length of given string.

Example:

#include<stdio.h>

int xstrlen(char *s)
{
    int length=0;
    while(*s!='\0')
    { length++; s++; }
    return (length);
}

int main()
{
    char d[] = "IndiaBIX";
    printf("Length = %d\n", xstrlen(d));
    return 0;
}

Output: Length = 8

Discussion:
17 comments Page 2 of 2.

Uday said:   9 years ago
Here, *s prints the first character of a given string. Then we need to increment *s++ instead of scan. Can anyone give me reply for my doubt?

L.priyanka said:   9 years ago
I need more detail explanation about this problem.

Ajay said:   10 years ago
I have problem in pointer. I didn't understand. Can you help me?

Shihabhasan said:   1 decade ago
sir I want to communicate with you.please response me.my skype id is:mehedi_cse40. please send me your skype id.

Shihab hasan said:   1 decade ago
Thanks a lot. You are great. Please write more and more so that we can learn C programming language. May God bless you.

Prince Bansal said:   1 decade ago
@Prince Varnwal:

*s is char pointer that holds character string.

When we want to print a string we use printf("%s",s). It will print whole string. It needs only base address.

s contains base address which is equal to &s[0] and printf will print characters until '\0' occurs.

Here, *s gives first character of input string where as s++ will increment base address by 1 byte.

When *s=='\0' encountered, it will terminate loop.

"Sorry for the poor English"

Prince varnwal said:   1 decade ago
What will do *s here?


Post your comments here:

Your comments will be displayed after verification.