String

A set of character is called string.String is also array of char type.

Syntax:
char string_name[size];

Here string_name is as like as variable name. Size is the number of character of the string.At the end of the string an additional terminating character(\0) will be added. For example

char name[10]

Here 10 char type memory space will be created that can be imagined as follows:

name[0]
name[1]
name[2]
name[3]
name[4]
name[5]
name[6]
name[7]
name[8]
name[9]

Here name[9] will contain ‘\0’. So you are allowed to input 9 characters into name[0] to name[8]. Therefor, your string size must be the number of character you want to input plus 1. For example, if you want to input 20 character you should set size 21 as follows:

char name[21]

Code example:

#include<stdio.h>
int main()
{
      char word[14]; //maximum 13 character can be input
      printf("Enter a word : ");
      scanf("%s",word);
      printf("Your entered word is : %s",word);
      return 0;
}

OUTPUT

Enter a word : hello
Your entered word is : hello

NOTE:

We used ‘&’ sign before a variable inside scanf() function but in case of string we just write variable name without ‘&’ sign.

scanf("%s",word);

Another important thing is: we used array name and index number inside third bracket but in case of string no need to write index number. For example

int a[10];
scanf("%d",&a[0]);

But

char s[10];
scanf("%s",s);

Actually, here s represents s[0] and first character will assign to s[0], second character will assign to s[1] and third character will assign to s[2] and so on automatically. We can change this sequence by setting the starting index number. For example:

scanf("%s",s[1]);

Here first character will assign to s[1], second character will assign to s[2], third character will assign to s[3] and so on.

Problem: Write a C program to input a word from keyboard and how each character followed by a new line.
Sample input: Bangladesh
Sample output:
B
a
n
g
l
a
d
e
s
h

Solution:

#include<stdio.h>
#include<string.h>
int main()
{
     char word[30];
     printf("Enter a word: ");
     scanf("%s",word);
     printf("Entered word: ");
     for(int i=0;word[i]!='/0';i++)
     {
             printf("%c\n",word[i]);
     }
     return 0;
}

OUTPUT

Enter a word: Bangladesh
Entered word:
B
a
n
g
l
a
d
e
s
h


Next Previous