MODULE-IV: STRINGS
STRINGS
“A string is a sequence of characters enclosed within double quotes”.
or
“String is an array of characters and terminated by NULL character which is denoted by
‘\0’.
A string is stored as a sequence of characters in an array terminated by ‘\0’ (NULL character).
Ex: Consider the String “DAVANGERE”.
This string is stored in the form of an array as shown below:
Declaring String variables
A string is declared like an array of characters.
Syntax: char string_name[size/length];
Where,
char: data type used to declare the strings or characters.
string_name: It specifies the name of the given string.
size: The size or maximum length (number of characters including ‘\0’) of the string is specified in
square brackets.
Length of the String: The ‘length’ is the number of characters stored in the string up to but not
including the null character.
Example
1. char name[21];
Size of the string is 21, means that it can store up to 20 characters plus one null character.
2. char str[10];
Size of the string is 10, means that it can store up to 10 characters plus one null character.
Initializing the Strings
We can initialize an array of characters (Strings) in the declaration itself.
Examples:
1. char a[9]={‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’, ‘\0’};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are
initialized with the characters in the order specified.
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
2. char
b[10]={‘R’,
‘A’, ‘M’, ‘A’, ‘\0’};
The compiler allocates 10 memory locations ranging from 0 to 9 and these locations are
initialized with the characters in the order specified. The remaining locations are
automatically initialized to null-characters as shown below:
3. char b[ ]={‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’, ‘\0’};
For this declaration, the compiler will set the array size to the total number of initial values. i.e.
9. The characters will be stored in these memory locations in the order specified as shown
below:
4. char b[ ]= “COMPUTER”;
Here, the string length is 8 bytes. But string size is 9 bytes. So, the compiler reserves 8+1
memory locations and these locations are initialized with the characters in the order
specified. The string is terminated by ‘\0’ by the compiler.
String Input / Output Functions
Strings can be read by using two ways(Input functions):
1. Using scanf() function
2. Using gets() function
Strings can be displayed on screen using two ways(Output functions):
1. Using printf() function
2. Using puts() function
Reading a String using scanf( )
It is possible to read a string using “scanf()”.
The conversion specification for reading a string using scanf() is “%s”.
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
The scanf() function stops reading characters when it finds the first white space character
(spaces, tabs and new line characters).
Example: char name[20];
printf(“Enter the name:”);
scanf(“%s”, name);
Printing a String using printf( )
The ‘printf()’ function prints the given string (all the characters but not the null character).
The printf() conversion specification for a string variable is “%s”.
Example: char name[20];
printf(“Enter the name:\n”);
scanf(“%s”, name);
printf(“The entered name is:%s”, name);
Output: Enter the name:
Rama
The entered name is:
Rama
Example C Program: Write a C program to read and display a string using scanf() and
printf().
#include<stdio.h>
void main()
{
char str[20];
printf(“Enter your name:\n”);
scanf(“%s”,str);
printf(“Entered name is:%s\n”,str);
}
Output:
Enter your name:
pesitm
Entered name is:
pesitm
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
Reading a String using gets( )
gets() function is used to read a sequence of characters (string) with spaces in between.
The ‘gets()’ function allows us to read an ‘entire line’ of input including whitespace characters.
Syntax: gets(string);
Example: char name[20];
printf(“Enter the name:”);
gets(name);
Printing a String using puts( )
‘puts()’ function is used for printing the given strings.
Whenever we want to display a sequence of characters stored in memory locations on the
screen, then puts() function can be used.
Syntax: puts(string);
Example: char name[20];
printf(“Enter the name:\n”);
gets(name);
printf(“The entered name is:\n”);
puts(name);
Output:
Enter the name:
Abdul Kalam
Entered name is:
Abdul Kalam
Difference between scanf() and gets()
scanf() gets()
when scanf() is used to read string input it stops when gets() is used to read input it stops reading
reading when it encounters whitespace, newline input when it encounters newline or End Of File.
or End Of File It does not stop reading the input on
encountering whitespace as it considers
whitespace as a string.
Scanf can read multiple values of different data gets will only get character string data
types
Example program Example program
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
char name[30]; char name[30];
printf(“Enter name’); printf(“Enter name’);
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
scanf(“%s”,name); gets(name);
printf(“%s”, name); puts(name);
} }
output: output:
Enter name Enter name
pesitm shimoga pesitm shimoga
pesitm pesitm shimoga
It is not used to read line of text It is used to read line of text
It is fast to take input. It takes one parameter that is the pointer to an
array of char
Difference between gets() and puts()
gets() puts()
“gets” is a C library function that reads a line “puts” is a C library function that writes a string
from stdin (standard input) and stores it in the to stdout or standard output.
pointed string.
Example: char name[20]; Example: char name[20];
printf(“Enter the name:”); printf(“Enter the name:\n”);
gets(name); gets(name);
printf(“The entered name is:\n”);
puts(name);
The gets function helps to scan a line of text The puts function helps to display a string on a
from a standard input device. standard output device.
The gets function returns string on success; The puts function returns a non-negative value if
however, it will return NULL or EOF if there are successful; if unsuccessful, it will return EOF
no characters to read. (End of File).
String Manipulation Functions
The standard library ‘string.h’ contains many functions for the string manipulation.
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
1. strlen(str) and: The length of a string
The ‘strlen()’ function can be used to find the length of the string in bytes.
This function calculates the length of the string up to but not including the ‘null character’.
Syntax
length= strlen(str);
Where,
‘str’ is a string.
‘length’ is an integer representing the length of ‘str’ in bytes excluding the null character.
Example: Write a C program to demonstrate the usage of strlen().
#include<stdio.h>
#include<string.h>
void main()
{
char str[10]= “hello”;
int length;
length=strlen(str);
printf(“Length of the string is=%d\n”,length);
}
Output: Length of the string is=5
Example: Write a C program to find the length of string without using strlen() function.
#include<stdio.h>
void main()
{
char str[];
int length=0;
printf(“Enter the string\n”);
gets(str);
while(str[length]!=’\0’)
{
length ++;
}
printf(“Length of the string is=%d\n”, length);
}
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
Output:
Enter the string
Good morning
Length of the string is=12
2. strcpy ( ): String Copy
Syntax: strcpy(dest,src);
Where,
dest: it is the destination string
src: it is the source string.
The ‘strcpy()’ function copies the contents of source string src to destination string dest
including ‘\0’.
The strcpy() function copies characters from the source string to the destination string until it
finds null character.
Example: Write a C program to demonstrate the usage of strcpy().
#include<stdio.h>
#include<string.h>
void main()
{
char src[10]= “string”,dest[10];
strcpy(dest,src);
printf(“The Source String=%s\n The Destination String=%s”,src,dest);
}
Output: The Source String =string
The Destination String =string
Example: Write a C program to copy string without using strcpy() function.
#include<stdio.h>
void main()
{
char src[30,dest[30];
int i;
printf(“Enter the source string\n”);
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
gets(src);
for(i=0; src[i]!=’\0’; i++)
{
dest[i] = src[i];
}
dest[i]=’\0’;
printf(“copied string is=%d\n”, dest);
}
Output:
Enter the string
rahul
copied string is= rahul
3. strncpy(dest,src,n): String Number Copy
Syntax: strncpy(dest,src,n);
Where,
dest: it is the destination string.
src: it is the source string.
n: n is the number of characters to be copied into destination string.
‘strncpy()’ function is used to copy ‘n’ characters from the source string src to the
destination string dest.
Examples: Write a C program to demonstrate the usage of strncpy().
#include<stdio.h>
#include<string.h>
void main()
{
char src[10]= “Computer”, dest[10];
strncpy(dest,src,3);
printf (“The Source String=%s\n The Destination String=%s”,src,dest);
}
Output: The Source String=Computer
The Destination String= Com
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
4. strcat(s1,s2): String Concatenate(Joining two strings together)
Syntax strcat(s1,s2);
Where,
s1: It is the first string
s2: It is the second string
The ‘strcat()’ function is used to concatenate or join the two strings.
The ‘strcat()’ function copies all the characters of string s2 to the end of string s1. The
NULL character of string s1 is replaced by the first character of s2.
Example: Write a C program to demonstrate the usage of strcat().
#include<stdio.h>
#include<string.h>
void main()
{
char s1[15]= “Good”;
char s2[15]= “Morning”;
strcat(s1,s2);
printf(“The concatenated String=%s”,s1);
}
Output:
The concatenated String=GoodMorning.
Example: Write a C program to demonstrate string concatenation without using strcat().
#include<stdio.h>
void main()
{
char s1[15], s2[15];
int i, len=0;
printf("Enter string1\n");
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
gets(s1);
printf("Enter string2\n");
gets(s2);
for (i=0; s1[i]!='\0'; i++)
{
len++;
}
for (i=0; s2[i]!='\0'; i++)
{
s1[len] = s2[i];
len++;
}
s1[len] = '\0';
printf("The concatenated String=%s",s1);
}
Output
Enter string1
good
Enter string2
moring
The concatenated String=goodmoring
5. strncat(s1,s2,n)- String Number Concatenate
Syntax strncat(s1,s2,n);
Where,
s1: It is the first string
s2: It is the second string
n: It is the number of characters of string s2 to be concatenated.
The ‘strncat()’ function is used to concatenate or join n characters of string s2 to the end
of string s1.
Example: Write a C program to demonstrate the usage of strncat().
#include<stdio.h>
#include<string.h>
void main()
{
char s1[15]= “Good”;
char s2[15]= “Morning”;
strncat(str1,str2,4);
printf(“The concatenated String=%s”,str1);
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
}
Output: The concatenated String=GoodMorn.
6. strcmp(s1,s2): String Compare
Syntax strcmp(s1,s2);
Where,
s1: It is the first string.
s2: It is the second string.
This function is used to compare two strings.
The comparison starts with first character of each string. The comparison continues till the
corresponding characters differ or until the end of the character is reached.
The following values are returned after comparison:
1. If two strings are equal, the function returns 0.
2. If s1 is greater than s2, a positive value is returned.
3. If s1 is less than s2, then the function returns a negative value.
Example: Write a C program to demonstrate the usage of strcmp().
#include<stdio.h>
#include<string.h>
void main()
{
char s1[10]=”Hello”;
char s2[10]=”Hey”;
if(strcmp(s1,s2)==0)
printf(“The two strings are identical”);
else
printf(“The two strings are not identical”);
}
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
Example: Write a C program to compare two strings without using strcmp().
#include<stdio.h>
void main()
{
char s1[10], s2[10];
int i,flag=0;
printf("Enter string1\n");
gets(s1);
printf("Enter string2\n");
gets(s2);
for(i=0;s1[i]!='\0'||s2[i]!='\0';i++)
{
if(s1[i]!=s2[i])
{
flag=1;
break;
}
}
if(flag==1)
printf("strings are different");
else
printf("The two strings are identical");
}
output
Enter string1
pes
Enter string2
pesitm
strings are different
7. strncmp(s1,s2,n): String Number Compare
Syntax: strncmp(s1,s2,n);
Where,
s1: It is the first string.
s2: It is the second string.
n: It is the number of characters to be compared.
This function is used to compare first n number of characters in two strings.
The comparison starts with first character of each string. The comparison continues till the
corresponding characters differ or until the end of the character is reached or specified numbers of
characters have been tested.
The following values are returned after comparison:
1. If two strings are equal, the function returns 0.
2. If s1 is greater than s2, a positive value is returned.
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
3. If s1 is less than s2, then the function returns a negative value.
Example: Write a C program to demonstrate the usage of strcmp().
#include<stdio.h>
#include<string.h>
void main()
{
char s1[10]=”Hello”;
char s2[10]=”Hey”;
if(strcmp(s1,s2,2)==0)
printf(“The first two characters in the strings are identical”);
else
printf(“The first two characters in the strings are not identical”);
}
Reversing a string
To reverse a string we just need to swap the first character with the last, second character with the
second last character, so on and so forth.
Write a C program to reverse a string.
#include<stdio.h>
void main()
{
char str[20],temp;
int i,j,len=0;
printf(“Enter the string: “);
gets(str);
for(i=0;str[i]!='\0';i++)
{
len++;
}
j=len-1;
for(i=0;i<j;i++)
{
temp=str[j];
str[j]=str[i];
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
str[i]=temp;
j--;
}
printf(“The reversed string is: “);
puts(str);
}
Output
Enter the string: pesitm
The reversed string is: mtisep
Converting characters of a string into upper case
✔ In memory the ASCII codes are stored instead of the 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 to upper case, then we just need to subtract
32 from the ASCII value of the character.
Write a C program to convert characters of a string to upper case.
#include<stdio.h>
void main()
{
char str[30];
int i;
printf(“Enter the string: “);
gets(str);
for(i=0;str[i]!=’\0’;i++)
{
if(str[i]>=’a’ && str[i]<=’z’)
str[i]=str[i]-32;
}
printf(“The string converted into upper case is: “);
puts(str);
}
Output
Enter the string: pesitm
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
The string converted into upper case is: PESITM
Converting characters of a string into lower case
✔ In memory the ASCII codes are stored instead of the 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 to upper case, then we just need to add 32
from the ASCII value of the character.
Write a C program to convert characters of a string to lower case.
#include<stdio.h>
void main()
{
char str[30];
int i;
printf(“Enter the string: “);
gets(str);
for(i=0;str[i]!=’\0’;i++)
{
if(str[i]>=’A’ && str[i]<=’Z’)
str[i]=str[i]+32;
}
printf(“The string converted into lower case is: “);
puts(str);
}
Output
Enter the string: PeSitM
The string converted into lower case is: pesitm
Write a program to find whether a given string is palindrome or not.
#include<stdio.h>
void main()
{
char s1[10], s2[10];
int i,j,flag=0,len=0;
printf("Enter string\n");
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga
gets(s1);
for(i=0;s1[i]!='\0';i++)
{
len++;
}
j=len-1;
for(i=0;s1[i]!='\0';i++)
{
s2[j]=s1[i];
j--;
}
s2[len]=’\0’;
for(i=0;s1[i]!='\0'||s2[i]!='\0';i++)
{
if(s1[i]!=s2[i])
{
flag=1;
break;
}
}
if(flag==1)
printf("string is not a palindrome");
else
printf("String is palindrome");
}
Output
Enter string
pes
string is not a palindrome
COMPILED BY Mrs. Suchitha H S, Dept. Of CSE, PESITM,Shivamoga