Pop Module 4 Strings Notes 3
Pop Module 4 Strings Notes 3
Prepared by
CHANDANA D.C
Assistant professor
Information Science and Engineering Department
MODULE-4
Strings and Pointers: Introduction, string taxonomy, operations on strings,
Miscellaneous string and character functions, arrays of strings. Pointers:
Introduction to pointers, declaring pointer variables, Types of pointers, passing
arguments to functions using pointers
Module 4 Principles of programming using C
MODULE-4
STRINGS
1. Introduction to Strings
A group of characters together is called string.
String is always enclosed within double quotes(“:”)
String always ends with deli meter (NULL,’\0’).
Example:
1. Char str []={‘H’, ’e’, ’l’, ’l’, ’o’, ’\0’};
Here compiler will automatically calculate the size based on the number of elements
initialized.so,in this example 6 memory slots will be reserved to store the string variable.
Char str[100];
Then str can be read from the user by using three ways:
Scanf(“%s”,str);
The main drawback with this function is that it terminates as soon as it finds a blank space.
Example: if the user enters “Hello world”, then str will contain only “Hello”. This is because the
moment a blank space is encountered, the string is terminated by the scanf() function.
Syntax: gets(str);
gets() is a simple function that overcomes the drawbacks of scanf().The gets() function takes the
CHANDANA D.C, Dept.of.ISE, VemanaIT Page 2
Module 4 Principles of programming using C
Example:
Writing strings:
Printf(“%s”,str);
The next method of writing a string is by using the puts function.The string can be displayed by
writing
Puts(str);
Puts() is a simple function that overcomes the drawbacks of printf ().the puts() function writes a
line of output on the screen. It terminates the line with a newline character (‘\n’).it returns an
EOF(end of file)(-1)if an error occurs and returns a positive number on success.
Example program:
2.String taxonomy
In c we can store a string either in fixed length format or in variable length format.
string
Fixed Variable
length length
Length Delimited
controlled
When storing a string in a fixed length format, you need to specify an appropriate size for the
string variable. If the size is too small, then you will not be able to store all the elements in the
string. On the other hand, if the string size is large, then unnecessarily memory space will be
wasted.
Example: Declare string variable to store the name of a student. If student has a long name of
say 20 characters, then the string can be expanded to accommodate 20 characters, on the other
hand, a student name has only 5 characters, then the string variable can be contracted to store
only 5 characters.
In length controlled string you need to specify the number of characters in the string. This count
is used by string manipulation function to determine the actual length of the string variable.
Delimited string:
In this format the string is ended with a delimiter. The delimiter is then used to identify the end
of the string.
For example, in English language every sentence is ended with a full-stop, similarly in C we can
CHANDANA D.C, Dept.of.ISE, VemanaIT Page 4
Module 4 Principles of programming using C
use any character such as comma, semicolon, colon, dash, null character etc. as the delimiter of a
string. However, the null character is the most commonly used string delimiter in the C language.
3.String operations:
1. Length operation:
The number of characters in the string constitutes the length of the string.
Example: Length (“C programming is fun”)
Output: return 20
Example program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str[100],i=0,length;
Clrscr();
Printf(“\n enter the string:”);
gets(str);
while(str[i]!=’\0’)
i++;
length=I;
printf(“\\n the length of the string is:%d”,length);
getch();
}
2.Converting characters of a string into upper case:
We have already seen that in memory the ASCII codes are stored instead of the real value.
The ASCII code for A-Z varies from 65 to 91 and ASCII code for a-z ranges from 97-123.
If we have to convert a lower case character to upper case then we just need to subs tract 32
from the ASCII value of the character.
Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str[100],upper_str[100];
int i=0,j=0;
printf(“\n enter the string:”);
gets(str);
while(str[i]!=”\0”)
CHANDANA D.C, Dept.of.ISE, VemanaIT Page 5
Module 4 Principles of programming using C
{
if(str[i]>=”a” && str[i]<=”z”)
upper_str[j]=str[i]-32;
else
upper_str[i]=str[i];
i++;
j++;
}
Upper_str[j]=”\0”;
Printf(“\n the string converted into upper case is:”);
Puts(upper_str);
return 0;
}
Output:
The ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z ranges from 97-
123.
If we have to convert an upper case character into lower case, then we just need to add 32
to its ASCII value.
Printf(“\n the string converted into lower case is:”);
Output: Puts(lower_str);
return 0;
Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str[100],upper_str[100];
int i=0,j=0;
printf(“\n enter the string:”);
gets(str);
while(str[i]!=”\0”)
{
if(str[i]>=”a” && str[i]<=”z”)
lower_str[j]=str[i]-32;
else
lower_str[i]=str[i];
i++;
j++;
}
lower_str[j]=”\0”;
}
If s1 and s2 are two strings, then concatenation operation produces a string which contains
characters of s1 followed by the characters of s2.
Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
Char str1[100],str2[100],str3[100];
int i=0,j=0;
printf(“\n enter the first string :”);
gets(str1);
printf(“\n enter the second string:”);
gets(str2);
while(str1[i]!=’\0’)
{
Str3[j]=str1[i];
i++;
j++;
}
i=0;
while(str2[i] !=’\0’)
{
Str3[j]=str2[i];
i++;
j++;
Str3[j]=’\0’;
Puts(str3);
getch();
return 0;
}
Output:
5.Appending strings:
Appending one string to another involves copying the contents of the source string at the
end of the destination string.
Example: if s1 and s2 are two strings, then appending s1 to s2 means we have to add the
contents of s1 to s2.
Here s1 is the source string and s2 is the destination string. The appending operation
would leave the source string s1 unchanged and the destination string s2=s2+s1.
Example program:
#include <stdio.h>
#include<conio.h>
main()
{
Char Dest_str[100],source_str[50];int i=0,j=0;
printf(“\n enter the source string:”);
gets(source_str);
printf(“\n enter the destination string:”);
gets(Dest_str);
while(Dest_str[i]!=’\0’)
i++;
while(source_str[j]!=’\0’)
{
Dest_str[i]=source_
str[j];i++;
j++;
}
Dest_str[i]=’\0’;
Printf(“\n After appending , the destination string is :”);
Puts(Dest_str);
return 0;
}
CHANDANA D.C, Dept.of.ISE, VemanaIT Page 8
Module 4 Principles of programming using C
Output:
If s1 and s2 are two strings then comparing two strings will give either of these results:
1. S1 and S2 are equal
2 . S1> S2,when in dictionary order s1 will come after s2.
3 S1<S2 ,when in dictionary order s1 precedes s2.
Example program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
Char str1[50],str2[50];
\int i=0,len1=0,len2=0,same=0;
printf(“\n enter the first string :”);
gets(str1);
printf(“\n enter the second string ”);
gets(str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1==len2)
{
While(i=len1)
{
if(str1[i]==str2[i])i++;
else
break;
}
if(i==len1)
{
Same=1;
Printf(“\n the two strings are equal”);
}
}
if(len1!=len2)
printf(“\n the two strings are not equal ”);
if (same==0)
{
if(str1[i]>str2[i])
{
printf(“\n string1 is greater
than string2”);else
if(str1[i]<str2[i]))
printf(“\n string2 is greater than string1”);
}
}
return 0;
}
OUTPUT
Enter the first string: Hello
Enter the second string: Hello
The two strings are equal
7.Reversing a string:
If s1=“Hello”, then reverse of s1=”olleH”.To reverse a string we just need to swap the first
character with the last. Second character with the second last character and so on.
Note:
There is a library function strrev (s1) that reverses all the characters in the string except
the null character. It is defined in string.h.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
Char str[100],reverse_str[100],temp;
int i=0,j=0;
printf(“\n enter the string”);
gets(str);
j=strlen(str)-1;
while(i<j)
{
temp=str[j];
str[j]=str[i];
str[i]=temp;
i++;
j--;
}
CHANDANA D.C, Dept.of.ISE, VemanaIT Page 10
Module 4 Principles of programming using C
Output:
Enter the string :Hi there
The reversed string is:ereht iH
In order to extract a substring from the main string we need to copy the content of the string
starting from the first position to the nth position where n is the number of characters to be
extracted.
Example:
If s1=”Hello world”,then substr_left(s1,7)=Hello w
In order to extract a substring from the right side of the main string we need to first calculate the
position.
Example:
To extract a substring from a given string requires information about three things.The main
string the position of the first character of the substring in the given string and maximum number
of characters/length of the substring.
Example:
11.Insertion:
The insertion operation insert a string S, in the main text T, at the Kth position. The general syntax of
this operation is : INSERT(text,position,string).
Example: INSERT(“xyzxyz”,3,”AAA”)=”xyzAAAxyz”.
#include<stdio.>
#include<conio.h>
main()
{
Char text[100], str[20], ins_text[100];
int i=0,j=0,k=0,pos;
Printf(“\n enter the main text:”);
gets (text);
printf(“\n enter the string to be inserted:”);
gets(str);
printf(“\n enter the position at which the string has to be inserted:””);
scanf(“%d”,&pos);
ehile(text[i]!=’\0’)
{
if(i==pos)
{
While(str[k]!=’\0’)
{
ins_text[j]=str[k];
j++;
k++;
}
}
12.Indexing:
Index operation returns the position in the string where the string pattern first occurs.
Example:
INDEX(“Welcome to the world of programming”,”world”)=15
13 Deletion:
Example:
DELETE(“ABCDXXXABCD”,5,3)=”ABCDABCD”
Program:
#include<stdio.h>
#include<conio.h>
main()
{
Char text[200],str[20],new_text[200];
int i=0,j=0,found=0,k,n=0,copy_loop=0;
printf(“\n enter the main text:”);
gets(text);
fflush(stdin);
printf(“\n enter the string to be deleted:”);
gets(str);
fflush9stdin);
while(text[i]!=’\0’)
{
j=0,found=0,k=i;
while(text[k]==str[j] && str[j]!=’\0’)
{
k++;
j++;
if(str[j]==’\0’)
copy_loop=k;
new_text[n]=text[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]=’\0’;
printf(“\n the new string is :”);
puts(new_text);
getch();
return 0;
Output:
14.Relpacement:
Replacement operation is used to replace the pattern p1 by another pattern t2 . This is done by
writing, REPLACE (text, pattern1, pattern2)
Example:
(“AAABBBCCC”,”BBB”,”X”)=AAAXCCC
The strcat() function appends the string pointed by str2 to the end of the string pointed to by str1.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[50]=””Programming”;
Strcat(str1,str2);
return 0;
Output:
Str1:Programming in c
2.strncat() function:
Syntax:
char *strncat(char *str1,const char *str2,size_t n);
This appends the string pointed to by str2 to the end of the string pointed to by str1 upto n
characters long.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[50]=”programming”;
Strncat(str1,str2,2);
Printf(“\n str1:%s”,str1);
return 0;
Output:
Str1:programming in
2. Strchr() function:
Syntax:
This function searches for the first occurrence of the character c in the string pointed to by the
argument str. The function returns a pointer pointing to the first matching character, or null if no
match was found.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char *pos;
Pos=strchr(str,’n’);
if(pos)
else
return 0;
Output:
3.Strrchr()function:
Syntax:
The strchr() function searches for the first occurrence of the character c beginning at the rear end
and working towards the front in the string pointed to by the argument str.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char *pos;
if(pos)
else
return 0;
Output:
3.strcmp() function:
Syntax:
the strcmp compares the string pointed to by str1 to the string pointed to by str2.The function
return zero if the strings are equal. Otherwise,it returns a value less than zero or greater than zero
if str1 is less than or greater than str2 .
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[10]=”HELLO”;
Char str2[10]=”HEY”;
if(strcmp(str1,str2)==0)
else
return 0;
Output:
4.Strcpy() function:
Syntax:
This function copies the string pointed to by str2 to str1 including the null character of str2.it
returns the argument str1.
Example:
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str1[10]=”HELLO”;
Char str2[10]=”HEY”;
strncpy(str1,str2,2)
printf(“\nstr1:%s”,str1);
return 0;
Output:
HE
5.strlen() function:
Syntax:
This function calculates the length of the string str upto but not including the null character, i.e
the function returns the number of characters in the string.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str[]=”HELLO”;
return 0;
Output:
Length of str is :5
6.strstr() function:
Syntax:
The function is used to find the first occurrence of string str2 in the string str1. It returns a
pointer to the first occurrence of str2 in str1.If no match is found then null pointer is returned.
Example:
#include<stdio.h>
#include<string.h>
int main()
Char str2[]=”DAY”;
Char *ptr;
Ptr=strstr(str1,str2));
if(ptr)
else
return 0;
Output:
Substring found
Array of string:
Char name[20][30];
Here the first index will specify how many strings are needed and the second index specifies the
length of every individual string.So here we allocate space for 20 names where each name can be
a maximum of 30 characters long.
Syntax:
Char name[5][10]={“Ram”,”Mohan”,”Shyam”,”Hari”,”Gopal”};
Name[0] R A M \0
M O H A N \0
Name[1]
S H Y A M \0
Name[2]
H A R I \0
Name[3]
G O P A L \0
Name[4]
Write functions to implement string operations such as compare, concatenate, string length. Convince
the parameter passing techniques.
#include<stdio.h>
#include<stdlib.h>
int length(char str[]);
int compare(char str1[],char str2[]);
void concatenate(char str1[],char str2[]);
void main()
{
char str1[30],str2[30];
int choice,a;
printf("Enter 1 - String Comparision\n");
printf("Enter 2 - String Length\n");
printf("Enter 3 - String Conctenation\n");
printf("Enter 4 - Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter String 1 :");
scanf("%s",str1);
printf("Enter String 2 :");
scanf("%s",str2);
a = compare(str1,str2);
if(a == 0)
{
printf("%s and %s are equal\n",str1,str2);
}
else
{
printf("%s and %s are not equal\n ",str1,str2);
}
break;
case 2: printf("Enter String :");
scanf("%s",str1);
a = length(str1);
printf("Length of %s = %d\n",str1,a);
break;
case 3: printf("Enter String 1 :");
scanf("%s",str1);
printf("Enter String 2 :");
scanf("%s",str2);
concatenate(str1,str2);
break;
case 4: exit(0);
break;
default : printf("Enter proper choice\n");
exit(0);
}
}
int length(char str[])
{
int i = 0;
while(str[i] !='\0')
{
i++;
}
return i;
}
int compare(char str1[],char str2[])
{
int i = 0;
while(str1[i] == str2[i])
{
if(str1[i] == '\0' || str2[i] == '\0')
break;
i++;
}
return str1[i] - str2[i];
}
void concatenate(char str1[] ,char str2[])
{
int i = 0, j = 0;
while(str1[i] !='\0')
{
i++;
}
while(str2[j] !='\0')
{
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0';
printf("Concatenated string is %s \n",str1);
}
Write a program to check whether a given string is palindrome or not. (without using any built-
in string function
#include <stdio.h>
#include <string.h>
int main(){
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
return 0;
}
Write a ‘C’ function to count the number of vowels and consonants in a string.
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000];
int i,vowels=0,consonants=0;
printf("Enter the string : ");
gets(s);
for(i=0;s[i];i++)
{
if((s[i]>=65 && s[i]<=90)|| (s[i]>=97 && s[i]<=122))
{
vowels++;
else
consonants++;
}
}
printf("vowels = %d\n",vowels);
printf("consonants = %d\n",consonants);
return 0;
}
}
QUESTION BANK
1. Define string? With example explain how to declare and initialization of stings 5M
2. Explain string input/output functions with examples. 8M
3. List and explain different types of string taxonomy 5M
4. List and Explain Any Five String Operations 10M
5. With example explain array of strings 5 M
6. Explain any five string manipulation functions with example. 10M
7. Write a program to check whether a given string is palindrome or not. (without using any
built-in string function). 5M
8. Write a ‘C’ function to count the number of vowels and consonants in a string. 5M
9. Write a C program to swap two strings. 5M
10. Mention the purpose of a Null Character in C strings 2M
11. Write functions to implement string operations such as compare, concatenate, string length. Convince
the parameter passing techniques.10M
*****************"If you want to shine like a sun, first burn like the sun."*****************