Strings
Strings
A string is a null-terminated character array. This means that after the last character, a null
character (‘\0’) is stored to signify the end of the character array.
The general form of declaring a string is
char str[size];
For example if we write,
char str[] = “HELLO”;
We are declaring a character array with 5 characters namely, H, E, L, L and O. Besides, a null
character (‘\0’) is stored at the end of the string. So, the internal representation of the string
becomes- HELLO’\0’. Note that to store a string of length 5, we need 5 + 1 locations (1
extra for the null character).
The name of the character array (or the string) is a pointer to the beginning of the string.
str[0] 1000 H
str[1] 1001 E
str[2] 1002
L
str[3] 1003
L
str[4] 1004 O
str[5] 1005
\0
If we declare a string by writing
char str[100];
Then str can be read from the user by using three ways
use scanf function
using gets() function
using getchar()function repeatedly
The string can be read using scanf() by writing
scanf(“%s”, str);
The string can be read by writing
gets(str);
gets() takes the starting address of the string which will hold the input. The string inputted using
gets() is automatically terminated with a null character.
The string can also be read by calling the getchar() repeatedly to read a sequence of single
characters (unless a terminating character is entered) and simultaneously storing it in a character
array.
i=0;
getchar(ch);
while(ch != '*’)
{ str[i] = ch;
i++;
getchar(ch);
} str[i] = '\0';
The string can be displayed on screen using three ways
use printf() function
using puts() function
using putchar()function repeatedly
The string can also be written by calling the putchar() repeatedly to print a sequence of single characters
i=0;
while(str[i] != '\0*)
{ putchar(str[i]);
i++;
}
The number of characters in the string constitutes the length of the string.
For example, LENGTH(“C PROGRAMMING IS FUN”) will return 20. Note that even blank spaces
are counted as characters in the string.
LENGTH(‘0’) = 0 and LENGTH(‘’) = 0 because both the strings does not contain any
character.
• In memory the ASCII code of a character is stored instead of its real value. The ASCII code for
A-Z varies from 65 to 91 and the ASCII code for a-z ranges from 97 to 123. So if we have to
convert a lower case character into upper case, then we just need to subtract 32 from the ASCII
value of the character.
ALGORITHM TO CONVERT THE CHARACTERS OF STRING INTO UPPER CASE
IF S1 and S2 are two strings, then concatenation operation produces a string which
contains characters of S1 followed by the characters of S2.
Name[1] M O H A N ‘\0
’
Name[2] S H Y A M ‘\0
’
Name[3] H A R I ‘\0
’
Name[4] G O P A L ‘\0
’
#include<stdio.h>
#include<conio.h>
main()
{
char names[5][10];
int i, n;
clrscr();