C Programming - Strings

Exercise : Strings - General Questions
6.
Which of the following function is more appropriate for reading in a multi-word string?
printf();
scanf();
gets();
puts();
Answer: Option
Explanation:

gets(); collects a string of characters terminated by a new line from the standard input stream stdin

#include <stdio.h>

int main(void)
{
   char string[80];

   printf("Enter a string:");
   gets(string);
   printf("The string input was: %s\n", string);
   return 0;
}

Output:

Enter a string: IndiaBIX

The string input was: IndiaBIX


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