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 1 of 2.

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"

Harsh patil said:   9 years ago
The string we have stored in the char D[] in main function will be pass the to the xstrlen(d) function and it will be parsed by *s and length will be counted by length++. So we need to have length ++ and s++.

Akshay said:   9 years ago
What is the difference between strlen and xstrlen ?

If there is no any difference so, what is the significance of xstrlen in C programming?

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?

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.

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.

Devi achsah said:   8 years ago
I don't know exactly. But I can share I what know. In this program xstrlen is only the name of the function.

Shendu said:   1 year ago
It's a very good website for gathering the knowledge.

Also, it is helpful for the placement. Thanks all.

Ahmed Shindy said:   3 years ago
"IndiaBix" length is 9 including the null termination character.

Am I right? Anyone, please clarify.
(1)

Vivek ladhe said:   6 years ago
@Akshay.

strlen is a std library function.
xstrlen is a user-defined function.


Post your comments here:

Your comments will be displayed after verification.