UNIT-5
STRINGS AND STRUCTURES
Strings
A string is a collection of characters which is treated as a single data item. A group of characters
enclosed in double quotes is known as a string constant. Some of the examples of string constants are:
1. “hai”
2. “hello world”
3. “My name is suresh”
In C programming, there is no predefined data type to declare and use strings. So, we use character arrays to
declare strings in C programs. The common operations that can be performed on a string are:
Reading and writing strings
Combining strings together
Copying one string to another
Comparing strings for equality
Extracting a portion of the string (substring)
Declaring and Initializing Strings
Like variables, we should declare strings before using them in the program. Since we already known
that strings are implemented as character arrays, the syntax for declaring a string is as shown below:
char stringname[size];
The size refers to the number of characters in the string. When the compiler assigns a character string to a
character array, it appends a ‘\0’ to the end of the array. So, the size of the character array should always be
number of characters plus 1.
Like numeric arrays and variables, character arrays can also be initialized when they are declared.
Some of the examples for initializing the string are as shown below:
char str[10] = {‘N’,’E’,’W’,’ ‘,’D’,’E’,’L’,’H’,’I’,’\0’};
or
char str[10] = “NEW DELHI”;
If less number of characters are provided than the size of the string, the rest of the characters are initialized
to ‘\0’. If we try to assign more characters then the size of the string, compiler gives an error.
Note: The string termination character ‘\0’, is used to terminate a string. In C, there is no data type
provided available. We maintain strings using character arrays. A string is a variable length structure
stored inside a fixed size array. The size of the array is often larger than the number of characters in the
string. So, the compiler must have some means to detect the end of the string. For this purpose we use ‘\0’.
Strings C Programming
Programs:
/*C program to declare a string */
#include<stdio.h>
main()
{
char str[6];
str[0] = 'h';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = '\0';
printf("%s",str);
return 0;
}
Output:
hello
/*C program to declare a string */
#include<stdio.h>
main()
{
char str1[6] = {'h','e','l','l','o','\0'};
char str2[] = {'h','e','l','l','o','\0'};
char str3[] = "hello world";
printf("%s",str1);
printf("\n%s",str2);
printf("\n%s",str3);
return 0;
}
Output:
hello
hello
hello world
/*C program to print a string */
#include<stdio.h>
main()
{
char str1[6] = {'h','e','l','l','o','\0'};
int i;
printf("%s\n",str1);
printf("\nPrinting the string using for loop...\n");
for(i = 0; i < 5; i++)
{
printf("%c",str1[i]);
}
return 0;
}
2
Strings C Programming
Output:
hello
Printing the string using for loop...
hello
/*C program to search for a character in a string */
#include<stdio.h>
main()
{
char str[15] = "good morning", ch;
int i;
printf("Enter a character to search: ");
scanf("%c",&ch);
for(i = 0; i < 15; i++)
{
if(str[i] == ch)
{
printf("Character found at position %d\n",(i+1));
}
}
return 0;
}
Output:
Enter a character to search: g
Character found at position 1
Character found at position 12
READING STRINGS
Using scanf function
Strings can be read from the terminal by using the familiar scanf function.
The format specifier to read strings is %s.
An example of reading a string using scanf function is shown below:
char str[10];
scanf(“%s”, str);
There is a downside of using scanf function for reading strings. The downside is, scanf cannot read
strings with white spaces.
For example, if we provide “New Delhi” as the string, scanf will read only “New” and the rest of
the characters are neglected or not processed.
So, to read “New Delhi”, we have to declare two character arrays and read “New” and “Delhi”
separately.
//EXAMPLE
#include<stdio.h>
main()
{
char line[20];
3
Strings C Programming
printf("Enter the line of text: ");
scanf("%s",line);
printf("%s",line);
return 0;
}
Output:
Enter the line of text: new delhi
New
USING getchar( ):
As we have learned that scanf function cannot be used for reading a line of text, we have to search
for other alternatives for reading a line of text which has white spaces embedded in it.
One alternative is to read the line of text character by character until the enter key (\n) is pressed.
Here we will use a predefined function called getchar( ) which reads a single character from the
terminal.
/* C program to read a line of text using getchar function */
#include<stdio.h>
main()
{
char line[20], ch;
int i;
printf("Enter the line of text: ");
for(i=0;ch!='\n';i++)
{
ch = getchar();
line[i] = ch;
}
line[i] = '\0';
printf("%s",line);
return 0;
}
Output:
Enter the line of text: hello good morning
hello good morning
USING gets( ):
There is a more efficient way for reading a line of text with white spaces. We can use the gets
function which is available in the stdio.h header file.
The purpose of gets function is to read a line of text from the terminal/keyboard. The usage of gets
function is as shown below:
gets(arrayname);
The arrayname in the above piece of code is the array in which we are going to store the string. By using the
gets function the above program can be rewritten as shown below:
/* C program to read a line of text using gets function */
#include<stdio.h>
main()
4
Strings C Programming
{
char line[20], ch;
int i;
printf("Enter the line of text: ");
gets(line);
printf("%s",line);
return 0;
}
Output:
Enter the line of text: good morning
good morning
Printing Text (printf, putchar and puts)
We can print strings in multiple ways. First is by using printf function. We can use the format
specifier %s to print a string. Let us consider the following example:
char str[4] = {‘h’,’a’,’i’,’\0’};
printf(“%s”, str);
The output of the above piece of code is “hai”.
The second way is to print the string character by character. For this purpose we can use the format
specifier %c for printing each character or we can use the predefined function putchar. The usage of this
function is as shown below:
putchar(ch);
In the above code, ch is the character that we want to print on the screen. By using the putchar function we
can print a line of text or string as shown below:
/* C program to print a string using putchar function */
#include<stdio.h>
main()
{
char line[20];
int i;
printf("Enter the line of text: ");
gets(line);
for(i=0;line[i]!='\0';i++)
{
putchar(line[i]);
}
return 0;
}
Output:
Enter the line of text: strings topic
strings topic
The last alternative for printing a string or a line of text is by using the predefined function puts. This
function is available in the stdio.h header file. By using the puts function we can rewrite the above program
as shown below:
5
Strings C Programming
/* C program to print a string using puts function */
#include<stdio.h>
main()
{
char line[20];
printf("Enter the line of text: ");
gets(line);
puts(line);
return 0;
}
Output:
Enter the line of text: strings topic
strings topic
STRING HANDLING FUNCTIONS
o The ‘C’ library provides a large number of string handling functions that can be used for performing
string manipulations.
o These functions are available in the header file string .h
o The header file is used for included whenever these functions are used.
C provides predefined functions for performing all the above operations or manipulations on strings. Most of
these predefined functions are available in string.h header file. The list of predefined functions is given
below:
Functions Purpose
scanf, gets, getchar To read a string
printf, puts, putchar To print a string
strcat To concatenate two strings
strcmp To compare two strings
strcpy To copy one string into another string
strstr To locate a substring in the string
strlen To calculate the length of the string
strrev To reverse the given string
[Link]( )
The strlen function is used to retrieve the length of a given string.
The return type of this function will be an integer.
The syntax of strlen function is as shown below:
strlen(string)
The parameter string can be either a character array or a string constant. The function returns the length of
the string which will be the number of characters in the string excluding the ‘\0’ character. Let us consider
an example:
6
Strings C Programming
//EXAMPLE PROGRAM
#include<stdio.h>
#include<string.h>
main()
{
char s1[100];
printf("Enter a string:");
gets(s1);
printf("Length of the string is %d",strlen
strlen(s1));
return 0;
}
OUTPUT:
Enter a string:hello world
Length of the string is 11
[Link]( )
The strcat predefined function is used to concatenate/join two strings together.
The syntax of the strcat function is shown below:
strcat(string1, string2)
The strcat function accepts two parameters which are strings. The string2 parameter can be either a
character array or a string constant.
The strcat function takes the content of string2 and merges it with the content in string1 and the
final result will be stored in string1. Let us see an example:
//EXAMPLE PROGRAM
#include<stdio.h>
#include<string.h>
main()
7
Strings C Programming
{
char str[25], cpy[25];
printf("\nEnter a string :");
gets(str);
strcat(cpy,str);
printf("\nn The copied string is %s",cpy);
return 0;
}
OUTPUT:
Enter a string :hello
The copied string is hello
[Link]( )
The strcmp predefined function is used to compare two strings.
After comparison, if the two strings are equal, then the function returns a 0.
Otherwise if the first string comes before the second string in alphabetical order, the function returns
a -1.
If the first string comes after the second string in alphabetical order, the function returns a 1 as the
return value.
The syntax of strcmp function
nction is as shown below:
strcmp(string1, string2)
Let us consider an example:
As seen from the above example, the strcmp function the first letter in both the strings and since they are
equal, now it compares the second letter in both the strings, which are e and a. Since, e comes after a
according to dictionary order, the result will be 1 which means, the string hello comes after (greater than)
the string hai.
//EXAMPLE PROGRAM
#include<stdio.h>
#include<string.h>
main()
{
char s1[25], s2[25];
int x;
printf("\nEnter a string :");
gets(s1);
8
Strings C Programming
printf("\nEnter another string :");
gets(s2);
x=strcmp(s1, s2);
if(x == 0)
puts("Two strings are equal");
else
puts("Two strings are not equal");
return 0;
}
OUTPUT:
Enter a string :computer
Enter another string :programming
Two strings are not equal
[Link]( )
The strcpy function is used to copy one string into another string.
This function can be used for creating a copy of an existing string.
The syntax of strcpy function is as shown below:
strcpy(string1, string2)
In the above syntax, the string2 can be either a string or string constant. The string in string2 is copied into
string1 and the result will be stored in string1. Let us consider an example:
//EXAMPLE PROGRAM
#include<stdio.h>
#include<string.h>
main()
{
char s1[25], s2[25];
int x;
printf("\nEnter a string :");
gets(s1);
strcpy(s2, s1);
printf("String in s2 is %s",s2);
return 0;
}
9
Strings C Programming
OUTPUT:
Enter a string :hello world
String in s2 is hello world
[Link]( )
The strstr function returns a character pointer of the first occurrence of the given substring in the
string.
If the substring is not found in the string, the function strstr returns NULL.
The syntax for strstr function is shown below:
strstr(string1, string2)
In the above syntax, strstr searches for string2 in the string1. If found, it returns a pointer to the first
occurrence of the string2 in string1. If not found, it returns NULL. Let us consider an example:
//EXAMPLE PROGRAM
#include<stdio.h>
#include<string.h>
main()
{
char s1[100]="programming
"programming languages are c,java,python";
c,java,python"
char *sub;
sub=strstr(s1,"languages");
printf("Substring is %s",sub);
return 0;
}
OUTPUT:
Substring is languages are c, java, python
[Link]( )
The strrev function is used to reverse a given string.
We can use this predefined function to check whether a given string is a palindrome or not.
The syntax for using the strrev function is as shown below:
10
Strings C Programming
strrev(string)
In the above syntax, the strrev function reverses the given string and returns it back. The content of the
string also changes. Let us see an example:
//EXAMPLE PROGRAM
#include<stdio.h>
#include<string.h>
main()
{
char s1[100];
printf("Enter a string:");
gets(s1);
strrev(s1);
printf("Reversed string is %s",s1);
return 0;
}
OUTPUT:
Enter a string:hello world
Reversed string is dlrow olleh
Other predefined functions
Some of the other predefined functions available in the string.h header file are shown in the below
table:
Function Purpose Syntax
strlwr To convert upper case letters to lower case strlwr(str1)
strupr To convert lower case letters to upper case strupr(str1)
/* C program to find the length of the string without using any string functions*/
#include <stdio.h>
int main()
{
char s[30];
int i,count=0;
printf("enter the string:");
gets(s);
for (i = 0; s[i] != '\0'; ++i)
count++;
printf("Length of the string: %d", count);
return 0;
}
Output:
enter the string:computer
Length of the string: 8
11
Strings C Programming
/* C program to locate a substring in the given string using strstr function */
#include<stdio.h>
#include<string.h>
main()
{
char str1[] = {'h','e','l','l','o','\0'};
char str2[] = "llo";
int index;
if(strstr(str1, str2) != NULL)
{
printf("Substring str2 is present in str1");
}
else
{
printf("Substring str2 is not present in str1");
}
return 0;
}
/* C program to check for a string palindrome */
#include<stdio.h>
#include<string.h>
main()
{
char org[10], dup[10];
printf("Enter a string: ");
gets(org);
strcpy(dup, org);
strrev(org);
if(strcmp(org, dup))
{
printf("Entered string is not a palindrome!");
}
else
{
printf("Entered string is a palindrome");
}
return 0;
}
Output:
Enter a string: madam
Entered string is a palindrome
// Program to reverse the string without using string functions
#include <stdio.h>
int main()
{
char ch[20];
int count=0,i;
12
Strings C Programming
printf("enter the text:");
gets(ch);
for(i=0;ch[i]!='\0';i++)
{
count++;
}
printf("the reverse string is\n");
for(i=count-1;i>=0;i--)
{
printf("%c",ch[i]);
}
return 0;
}
Output:
enter the text:hello
the reverse string is
olleh
// Program to compare two strings without strcmp( )
#include <stdio.h>
int main()
{
char s1[20],s2[20];
int i,flag=0;
printf("Enter string1:");
gets(s1);
printf("Enter string2:");
gets(s2);
for(i=0;s1[i]!='\0' && s2[i]!='\0';i++)
{
if(s1[i]!=s2[i])
{
flag=1;
break;
}
}
if(flag==0)
{
printf("same");
}
else
printf("not same");
return 0;
}
13
Strings C Programming
Output:
Enter string1:hello
Enter string2:hello
same
// C program to copy string without using strcpy
#include <stdio.h>
int main()
{
char s1[100], s2[100];
int i;
printf("Enter string s1: ");
gets(s1);
for (i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}
Output:
Enter string s1: welcome
String s2: welcome
// String concatenation without strcat
#include<stdio.h>
void main()
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
14
Strings C Programming
printf("\nConcatenated String is %s",str1);
}
Output:
Enter First String:hello
Enter Second String:good morning
Concatenated String is hellogood morning
15