SlideShare a Scribd company logo
HANDLING OF CHARACTER
STRINGS
INTRODUCTION
• A string is an array of characters
• Any group of characters defined between double
quotation marks is a constant string
– EXAMPLE: “Man is obviously made to think.”
• To include a double quote in the string to be
printed, use a back slash.
– EXAMPLE: printf(“Well Done !”);
– OUTPUT: Well Done!
– EXAMPLE: printf(“”Well Done!””);
– OUTPUT: “Well Done!”
INTRODUCTION
• Common operations performed on strings are:
– Reading and writing strings
– Combining strings together
– Copying one string to another
– Comparing strings for equality
– Extracting a portion of a string
DECLARING AND INITIALIZING
STRING VARAIBLES
• A string variable is any valid C variable name
and is always declared as an array
– SYNTAX: char string_name[size];
• The size determines the number of characters in
the string-name
– EXAMPLE: char city[10];
• When the compiler assigns a character string to
an character array, it automatically supplies a
null character (‘0’) at the end of the string
• The size should be equal to the maximum
number of characters in the string plus one
DECLARING AND INITIALIZING
STRING VARAIBLES
• Character arrays may be initialized when they
are declared
char city[9] = “NEW YORK”;
char city[9] = (‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’0’);
• When we initialize a character by listing its
elements, we must supply the null terminator
• Can initialize a character array without
specifying the number of elements.
DECLARING AND INITIALIZING
STRING VARAIBLES
• The size of the array will be determined
automatically, based on the number of elements
initialized.
char string[ ] = {'G','O','O','D','0'};
• Can also declare the size much larger than the
string size.
char str[10] = “GOOD”;
• Following will result in a compile time error.
char str[3] = “GOOD”;
DECLARING AND INITIALIZING
STRING VARIABLES
• We cannot separate the initialization from declaration
– char str[5];
– str = “GOOD”;
• Following is not allowed
– char s1[4]=”abc”;
– char s2[4];
– s2 = s1;
• The array name cannot be used as the left operand
of an assignment operator
READING STRING FROM TERMINAL
• Reading words
– The input function scanf can be used with %s format
specification to read in a string of character
char address[15];
scanf(“%s”, address);
– The problem with the scanf function is that it
terminates its input on the first white space it finds
– A white space include blanks, tabs, carriage returns,
form feeds and new lines
INPUT: NEW YORK
– Only the string “NEW” will be read into the array
address
– In the case of character arrays, the ampersand (&) is
not required before the variable name
– The scanf function automatically terminates the string
with a null character
READING STRING FROM TERMINAL
• C supports a format specification known as the
edit set conversion code %[..] that can be used
to read a line containing a variety of characters,
including whitespaces.
– char line[80];
– scanf(“%[^n]”,line);
– printf(“%s”,line);
• Will read a line of input from the keyboard and
display the same on the screen.
READING STRING FROM TERMINAL
• Reading a Line of Text
– We have used getchar function to read a single
character from the terminal
– This getchar function is used repeatedly to read
successive single characters from the input and place
them into a character array
– Thus an entire line of text can be read and stored in
an array
– The reading is terminated when the newline character
(‘n’) is entered and the null character is then inserted
at the end of the string
PROGRAM
#include <stdio.h>
main()
{
char line[100], character;
int c;
c = 0;
printf("Enter Text:n");
do
{
character = getchar();
line[c] = character;
c++;
} while(character != 'n');
c = c-1;
line[c] = '0';
printf("n%sn",line);
}
READING A LINE OF TEXT
• For reading string of text containing whitespaces
is to use the library function gets available in the
<stdio.h>
gets(str)
• It reads characters into str from the keyboard
until a new-line character is encountered and
then appends a null character to the string.
char line[80];
gets(line)
printf(“%s”,line);
• The last two statements may be combined as:
printf(“%s”,gets(line));
READING A LINE OF TEXT
• Does not check array-bounds, so do not input
more characters, it may cause problems
• C does not provide operators that work on
strings directly.
• We cannot assign one string to another directly.
string2 = “ABC”
string1 = string2;
• Are not valid.
• To copy the characters in string2 into sting1, we
may do so on a character-by-character basis.
PROGRAM
#include<stdio.h>
main()
{
char string1[30], string2[30];
int i;
printf("Enter a stringn");
scanf("%s",string2);
for(i=0;string2[i]!='0';i++)
string1[i]=string2[i];
string1[i] = '0';
printf("n");
printf("%sn",string1);
printf("Number of characters = %dn",i);
}
WRITING STRINGS TO SCREEN
• The printf function with %s format is used to print
strings to the screen
• The format %s can be used to display an array
of characters that is terminated by the null
character
printf(“%s”, name);
• This display the entire content of the array name
USING PUTCHAR ANS PUTS
• C supports putchar to output the values of
character variables.
char ch = 'A';
putchar(ch);
• This statement is equivalent to
printf(“%c”,ch);
• Can use this function repeatedly to output string
of characters stored in an array using a loop.
char name[6] = “PARIS”;
for(i=0;i<5;i++)
putchar(name[i]);
putchar(“n”);
USING PUTCHAR ANS PUTS
• To print the string values is to use the function
puts declared in the header file <stdio.h>
puts(str);
• str is a string variable containing a string value.
• This printf the value of the string variable str and
then moves the cursor to the beginning of the
next line on the screen.
char line[80];
gets(line);
puts(line);
• Reads a line of text from the keyboard and
display it on the screen.
ARITHMETIC OPERATIONS ON
CHARACTERS
• C allows to manipulate characters the same way
we do with the numbers
• Whenever a character constant or character
variable is used in an expression, it is
automatically converted into an integer value by
the system
x = ‘a’;
printf(“%dn”,x);
OUTPUT: 97
EXAMPLE: x = ‘z’ – 1;
• The value of z is 122 and the above statement
assign 121 to the variable x
ARITHMETIC OPERATIONS ON
CHARACTERS
• Can use character constants in relational
expressions
EXAMPLE: ch >= ‘A’ && ch <= ‘Z’
• Test whether the character contained in the
variable ch is an upper-case letter
• Can convert a character digit to its equivalent
integer using
x = character – ‘0’;
• Where x is defined as an integer variable and
character contains the character digit
• The character containing the digit ‘7’ then
x = ASCII value of ‘7’ - ASCII value of ‘0’
= 55 – 48 = 7
ARITHMETIC OPERATIONS ON
CHARACTERS
• The C library supports a function that converts a
string of digits into their integer values
• The function takes the form
X = atoi(string)
• EXAMPLE:
number = “1998”;
Year = atoi(number);
PUTTING STRINGS TOGETHER
• We cannot assign the string to another directly
• We cannot join two strings together by the
simple arithmetic addition
string3 = strin1 + string2;
string2 = string1 + “hello”;
• The process of combining two strings together is
called concatenation
COMPARISON OF TWO STRINGS
• C does not permit the comparison of two strings
directly
if(name1 == name2)
if(name == “ABC”)
• are not permitted
• It is therefore necessary to compare the two
strings to be tested, character by character
• The comparison is done until a mismatch or one
of the strings terminates into a null character,
whichever occur first
COMPARISON OF TWO STRINGS
i=0;
while(str1[i]==str2[i] && str1[i] != '0' && str2 != '0')
i = i+1;
if(str1[i] == '0' && str2 == '0')
printf("strings are equal");
else
printf("strings are not equal");
Lengths of strings
/* Lengths of strings */
#include <stdio.h>
main()
{
char str1[] = "To be or not to be";
char str2[] = ",that is the question";
int count = 0; /* Stores the string length */
while (str1[count] != '0') /* Increment count till we reach the string */
count++; /* terminating character. */
printf("nThe length of the string1 is", count);
count = 0; /* Reset to zero for next string */
while (str2[count] != '0') /* Count characters in second string */
count++;
printf("nThe length of the string2 is", count);
}
OUTPUT:
The length of the string1 is 18
The length of the string2 is 21
STRING-HANDLING FUNCTIONS
• C library supports large number of string-
handling functions
• Some are
Strings
There are several standard routines that work on string variables.
Some of the string manipulation functions are,
strcpy(string1, string2); - copy string2 into string1
strcat(string1, string2); - concatenate string2 onto the end of string1
strcmp(string1,string2); - 0 if string1 is equals to string2,
< 0 if string1 is less than string2
>0 if string1 is greater than string2
strlen(string); - get the length of a string.
strrev(string); - reverse the string and result is stored in
same string.
strcat() FUNCTION
• The strcat function joins two strings together
– SYNTAX:
strcat(string1, string2);
• string1 and string2 are character array
• string2 is appended to string1
• The null character at the end of the string1 is
removed and string2 is placed from there
• The string2 remains unchanged
Example
#include <stdio.h>
#include <string.h>
int main ()
{
char src[50], dest[50];
puts(“Enter a text1”);
gets(src);
puts(“nEnter a text2”);
gets(dest);
strcat(dest, src);
printf("Final destination string : |%s|", dest);
}
C program to concatenate two strings without using strcat()
#include<stdio.h>
void main(void)
{
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';
printf("nConcatenated String is %s",str1);
}
strcmp() FUNCTION
• Compares two strings identified by the arguments and
has a value 0 if they are equal
• If they are not, it has the numeric difference between
the first non-matching characters in the strings
strcmp(string1, string2);
– EXAMPLE:
strcmp(nam1, name2);
strcmp(name1, “John”);
strcmp(“Rom”, “Ram”);
strcmp(“their”, ”there”);
• The above statement will return the value of -9 which
is numeric difference between ASCII “i” and ASCII “r”
is -9
• If the value is negative the string1 is alphabetically
above string2
#include <string.h>
#include<conio.h>
void main(void)
{
char str1[25],str2[25];
int dif,i=0;
clrscr();
printf("nEnter the first String:");
gets(str1);
printf("nEnter the secondString;");
gets(str2);
while(str1[i]!='0'||str2[i]!='0')
{
dif=(str1[i]-str2[i]);
if(dif!=0)
break;
i++;
}
if(dif>0)
printf("%s comes after
%s",str1,str2);
else
{
if(dif<0)
printf("%s comes after
%s",str2,str1);
else
printf("both the strings are same");
}
}
C program to compare two strings using strcmp
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
printf("Enter the first stringn");
gets(a);
printf("Enter the second stringn");
gets(b);
if( strcmp(a,b) == 0 )
printf("Entered strings are equal.n");
else
printf("Entered strings are not equal.n");
}
strcpy() FUNCITON
• Works almost like a string-assignment operator
– SYNTAX:
strcpy(string1, string2);
• Assigns the content of string2 to string1
– EXAMPLE:
strcpy(city, “DELHI”);
• Assign the string “DELHI” to the string variable
city
strcpy(city1, city2);
• Assigns the contents of the string variable city2
to the string variable city1
Copy String Manually without using strcpy()
#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i=0; s1[i]!='0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='0';
printf("String s2: %s",s2);
}
strlen() FUNCTION
• This function counts and return the number of
characters in a string
– SYNTAX:
n = strlen(string);
• Where n is the integer variable which receives
the value of the length of the string
• The counting ends at the first null character
– EXAMPLE:
Ch = “NEW YORK”;
n = strlen(ch);
printf(String Length = %dn”, n);
– OUTPUT:
String Length = 8
TABLE OF STRINGS
• We use lists of character strings, such as
– List of name of students in a class
– List of name of employees in an organization
– List of places, etc
• These list can be treated as a table of strings and
a two dimensional array can be used to store the
entire list
– EXAMPLE:
student[30][15];
• is an character array which can store a list of 30
names, each of length not more than 15
characters
char city[ ][ ] = { “chandigarh”, “Madrad”, Ahmedab” };
ARRAYS OF STRINGS
• An array of strings is a two-dimensional
array. The row index refers to a particular
string, while the column index refers to a
particular character within a string.
Definition
char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING];
Example
char name[5][31];
Initialization
char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING] =
{ "initializer 1", "initializer 2", ... };
For example,
char name[5][31] = {“Logesh", "Jean", “ganesh", “moon",
“kumaran”};
Input and Output
Input
To accept input for a list of 5 names, we write
char name[5][31];
for (i = 0; i < 5; i++)
scanf(" %[^n]s", name[i]);
The space in the format string skips leading whitespace before
accepting the string.
Output
char name[5][31] = {"Harry", "Jean", "Jessica", "Irene", "Jim"};
printf("%s", name[2]);
Sorting of string
#include<stdio.h>
int main(){
int i,j,n;
char str[20][20],temp[20];
puts("Enter the no. of string to be sorted");
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
{ for(j=i+1;j<=n;j++){
{ if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf("The sorted stringn");
for(i=0;i<=n;i++)
puts(str[i]);
}
Search a name in a give list
#include<stdio.h> #include<string.h>
int main()
{
char name[5][10],found[10];
int j,i,flag=0;
printf("Enter a name :");
for(i=0;i<5;i++)
scanf("%s",name[i]);
printf("enter a searching stringn");
scanf("%s",found);
for(i=0;i<5;i++)
{
if(strcmp(name[i],found)==0)
{ flag=1; break; }
}
if(flag==1)
printf("String foundn");
else
printf("nString not found");
}

More Related Content

What's hot (20)

PPTX
Strings in C
Kamal Acharya
 
PPT
Strings in c
vampugani
 
PPTX
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
PDF
Managing I/O in c++
Pranali Chaudhari
 
PPTX
Enums in c
Vijayananda Ratnam Ch
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
PPTX
Union in C programming
Kamal Acharya
 
PPTX
C string
University of Potsdam
 
PPTX
C programming - String
Achyut Devkota
 
PPTX
Structures in c language
tanmaymodi4
 
PPTX
Data types in c++
Venkata.Manish Reddy
 
PPTX
Dynamic Memory Allocation in C
Vijayananda Ratnam Ch
 
PPTX
Datatype in c++ unit 3 -topic 2
MOHIT TOMAR
 
PPTX
Pointers in c++
sai tarlekar
 
PPTX
Arrays in Data Structure and Algorithm
KristinaBorooah
 
PPTX
Function in c program
umesh patil
 
PPTX
String In C Language
Simplilearn
 
PPTX
Function in C program
Nurul Zakiah Zamri Tan
 
PPT
Constants in C Programming
programming9
 
Strings in C
Kamal Acharya
 
Strings in c
vampugani
 
Managing I/O in c++
Pranali Chaudhari
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Functions in c++
Rokonuzzaman Rony
 
Union in C programming
Kamal Acharya
 
C programming - String
Achyut Devkota
 
Structures in c language
tanmaymodi4
 
Data types in c++
Venkata.Manish Reddy
 
Dynamic Memory Allocation in C
Vijayananda Ratnam Ch
 
Datatype in c++ unit 3 -topic 2
MOHIT TOMAR
 
Pointers in c++
sai tarlekar
 
Arrays in Data Structure and Algorithm
KristinaBorooah
 
Function in c program
umesh patil
 
String In C Language
Simplilearn
 
Function in C program
Nurul Zakiah Zamri Tan
 
Constants in C Programming
programming9
 

Viewers also liked (12)

PDF
BE Aerospace Syllabus of MIT, Anna University R2015
Appili Vamsi Krishna
 
DOC
Storage classess of C progamming
Appili Vamsi Krishna
 
PPTX
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
PDF
C language for Semester Exams for Engineers
Appili Vamsi Krishna
 
DOC
Difference between structure and union
Appili Vamsi Krishna
 
PPTX
Function C programming
Appili Vamsi Krishna
 
PPT
C programming for Computing Techniques
Appili Vamsi Krishna
 
DOCX
Types of storage class specifiers in c programming
Appili Vamsi Krishna
 
PPT
Pointers C programming
Appili Vamsi Krishna
 
PPT
User defined functions in C programmig
Appili Vamsi Krishna
 
PPTX
Planers machine
Bilalwahla
 
DOCX
Conventional machining vs. non conventional machining
onlinemetallurgy.com
 
BE Aerospace Syllabus of MIT, Anna University R2015
Appili Vamsi Krishna
 
Storage classess of C progamming
Appili Vamsi Krishna
 
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
C language for Semester Exams for Engineers
Appili Vamsi Krishna
 
Difference between structure and union
Appili Vamsi Krishna
 
Function C programming
Appili Vamsi Krishna
 
C programming for Computing Techniques
Appili Vamsi Krishna
 
Types of storage class specifiers in c programming
Appili Vamsi Krishna
 
Pointers C programming
Appili Vamsi Krishna
 
User defined functions in C programmig
Appili Vamsi Krishna
 
Planers machine
Bilalwahla
 
Conventional machining vs. non conventional machining
onlinemetallurgy.com
 
Ad

Similar to Handling of character strings C programming (20)

PDF
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
PDF
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
PPTX
introduction to strings in c programming
mikeymanjiro2090
 
PDF
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
PPTX
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
PDF
5 2. string processing
웅식 전
 
PPT
Operation on string presentation
Aliul Kadir Akib
 
PDF
PROBLEM SOLVING USING A PPSC- UNIT -3.pdf
JNTUK KAKINADA
 
PDF
String notes
Prasadu Peddi
 
PPTX
Strings in c++
Neeru Mittal
 
PPTX
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
PPT
Lecture 05 2017
Jesmin Akhter
 
PPTX
COm1407: Character & Strings
Hemantha Kulathilake
 
DOCX
Array &strings
UMA PARAMESWARI
 
PPSX
Strings
Dhiviya Rose
 
PDF
0-Slot21-22-Strings.pdf
ssusere19c741
 
PPTX
UNIT 4C-Strings.pptx for c language and basic knowledge
2024163103shubham
 
PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
introduction to strings in c programming
mikeymanjiro2090
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
5 2. string processing
웅식 전
 
Operation on string presentation
Aliul Kadir Akib
 
PROBLEM SOLVING USING A PPSC- UNIT -3.pdf
JNTUK KAKINADA
 
String notes
Prasadu Peddi
 
Strings in c++
Neeru Mittal
 
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
Lecture 05 2017
Jesmin Akhter
 
COm1407: Character & Strings
Hemantha Kulathilake
 
Array &strings
UMA PARAMESWARI
 
Strings
Dhiviya Rose
 
0-Slot21-22-Strings.pdf
ssusere19c741
 
UNIT 4C-Strings.pptx for c language and basic knowledge
2024163103shubham
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
Ad

Recently uploaded (20)

PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
infertility, types,causes, impact, and management
Ritu480198
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
Difference between write and update in odoo 18
Celine George
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
Controller Request and Response in Odoo18
Celine George
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 

Handling of character strings C programming

  • 2. INTRODUCTION • A string is an array of characters • Any group of characters defined between double quotation marks is a constant string – EXAMPLE: “Man is obviously made to think.” • To include a double quote in the string to be printed, use a back slash. – EXAMPLE: printf(“Well Done !”); – OUTPUT: Well Done! – EXAMPLE: printf(“”Well Done!””); – OUTPUT: “Well Done!”
  • 3. INTRODUCTION • Common operations performed on strings are: – Reading and writing strings – Combining strings together – Copying one string to another – Comparing strings for equality – Extracting a portion of a string
  • 4. DECLARING AND INITIALIZING STRING VARAIBLES • A string variable is any valid C variable name and is always declared as an array – SYNTAX: char string_name[size]; • The size determines the number of characters in the string-name – EXAMPLE: char city[10]; • When the compiler assigns a character string to an character array, it automatically supplies a null character (‘0’) at the end of the string • The size should be equal to the maximum number of characters in the string plus one
  • 5. DECLARING AND INITIALIZING STRING VARAIBLES • Character arrays may be initialized when they are declared char city[9] = “NEW YORK”; char city[9] = (‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’0’); • When we initialize a character by listing its elements, we must supply the null terminator • Can initialize a character array without specifying the number of elements.
  • 6. DECLARING AND INITIALIZING STRING VARAIBLES • The size of the array will be determined automatically, based on the number of elements initialized. char string[ ] = {'G','O','O','D','0'}; • Can also declare the size much larger than the string size. char str[10] = “GOOD”; • Following will result in a compile time error. char str[3] = “GOOD”;
  • 7. DECLARING AND INITIALIZING STRING VARIABLES • We cannot separate the initialization from declaration – char str[5]; – str = “GOOD”; • Following is not allowed – char s1[4]=”abc”; – char s2[4]; – s2 = s1; • The array name cannot be used as the left operand of an assignment operator
  • 8. READING STRING FROM TERMINAL • Reading words – The input function scanf can be used with %s format specification to read in a string of character char address[15]; scanf(“%s”, address); – The problem with the scanf function is that it terminates its input on the first white space it finds – A white space include blanks, tabs, carriage returns, form feeds and new lines INPUT: NEW YORK – Only the string “NEW” will be read into the array address – In the case of character arrays, the ampersand (&) is not required before the variable name – The scanf function automatically terminates the string with a null character
  • 9. READING STRING FROM TERMINAL • C supports a format specification known as the edit set conversion code %[..] that can be used to read a line containing a variety of characters, including whitespaces. – char line[80]; – scanf(“%[^n]”,line); – printf(“%s”,line); • Will read a line of input from the keyboard and display the same on the screen.
  • 10. READING STRING FROM TERMINAL • Reading a Line of Text – We have used getchar function to read a single character from the terminal – This getchar function is used repeatedly to read successive single characters from the input and place them into a character array – Thus an entire line of text can be read and stored in an array – The reading is terminated when the newline character (‘n’) is entered and the null character is then inserted at the end of the string
  • 11. PROGRAM #include <stdio.h> main() { char line[100], character; int c; c = 0; printf("Enter Text:n"); do { character = getchar(); line[c] = character; c++; } while(character != 'n'); c = c-1; line[c] = '0'; printf("n%sn",line); }
  • 12. READING A LINE OF TEXT • For reading string of text containing whitespaces is to use the library function gets available in the <stdio.h> gets(str) • It reads characters into str from the keyboard until a new-line character is encountered and then appends a null character to the string. char line[80]; gets(line) printf(“%s”,line); • The last two statements may be combined as: printf(“%s”,gets(line));
  • 13. READING A LINE OF TEXT • Does not check array-bounds, so do not input more characters, it may cause problems • C does not provide operators that work on strings directly. • We cannot assign one string to another directly. string2 = “ABC” string1 = string2; • Are not valid. • To copy the characters in string2 into sting1, we may do so on a character-by-character basis.
  • 14. PROGRAM #include<stdio.h> main() { char string1[30], string2[30]; int i; printf("Enter a stringn"); scanf("%s",string2); for(i=0;string2[i]!='0';i++) string1[i]=string2[i]; string1[i] = '0'; printf("n"); printf("%sn",string1); printf("Number of characters = %dn",i); }
  • 15. WRITING STRINGS TO SCREEN • The printf function with %s format is used to print strings to the screen • The format %s can be used to display an array of characters that is terminated by the null character printf(“%s”, name); • This display the entire content of the array name
  • 16. USING PUTCHAR ANS PUTS • C supports putchar to output the values of character variables. char ch = 'A'; putchar(ch); • This statement is equivalent to printf(“%c”,ch); • Can use this function repeatedly to output string of characters stored in an array using a loop. char name[6] = “PARIS”; for(i=0;i<5;i++) putchar(name[i]); putchar(“n”);
  • 17. USING PUTCHAR ANS PUTS • To print the string values is to use the function puts declared in the header file <stdio.h> puts(str); • str is a string variable containing a string value. • This printf the value of the string variable str and then moves the cursor to the beginning of the next line on the screen. char line[80]; gets(line); puts(line); • Reads a line of text from the keyboard and display it on the screen.
  • 18. ARITHMETIC OPERATIONS ON CHARACTERS • C allows to manipulate characters the same way we do with the numbers • Whenever a character constant or character variable is used in an expression, it is automatically converted into an integer value by the system x = ‘a’; printf(“%dn”,x); OUTPUT: 97 EXAMPLE: x = ‘z’ – 1; • The value of z is 122 and the above statement assign 121 to the variable x
  • 19. ARITHMETIC OPERATIONS ON CHARACTERS • Can use character constants in relational expressions EXAMPLE: ch >= ‘A’ && ch <= ‘Z’ • Test whether the character contained in the variable ch is an upper-case letter • Can convert a character digit to its equivalent integer using x = character – ‘0’; • Where x is defined as an integer variable and character contains the character digit • The character containing the digit ‘7’ then x = ASCII value of ‘7’ - ASCII value of ‘0’ = 55 – 48 = 7
  • 20. ARITHMETIC OPERATIONS ON CHARACTERS • The C library supports a function that converts a string of digits into their integer values • The function takes the form X = atoi(string) • EXAMPLE: number = “1998”; Year = atoi(number);
  • 21. PUTTING STRINGS TOGETHER • We cannot assign the string to another directly • We cannot join two strings together by the simple arithmetic addition string3 = strin1 + string2; string2 = string1 + “hello”; • The process of combining two strings together is called concatenation
  • 22. COMPARISON OF TWO STRINGS • C does not permit the comparison of two strings directly if(name1 == name2) if(name == “ABC”) • are not permitted • It is therefore necessary to compare the two strings to be tested, character by character • The comparison is done until a mismatch or one of the strings terminates into a null character, whichever occur first
  • 23. COMPARISON OF TWO STRINGS i=0; while(str1[i]==str2[i] && str1[i] != '0' && str2 != '0') i = i+1; if(str1[i] == '0' && str2 == '0') printf("strings are equal"); else printf("strings are not equal");
  • 24. Lengths of strings /* Lengths of strings */ #include <stdio.h> main() { char str1[] = "To be or not to be"; char str2[] = ",that is the question"; int count = 0; /* Stores the string length */ while (str1[count] != '0') /* Increment count till we reach the string */ count++; /* terminating character. */ printf("nThe length of the string1 is", count); count = 0; /* Reset to zero for next string */ while (str2[count] != '0') /* Count characters in second string */ count++; printf("nThe length of the string2 is", count); } OUTPUT: The length of the string1 is 18 The length of the string2 is 21
  • 25. STRING-HANDLING FUNCTIONS • C library supports large number of string- handling functions • Some are
  • 26. Strings There are several standard routines that work on string variables. Some of the string manipulation functions are, strcpy(string1, string2); - copy string2 into string1 strcat(string1, string2); - concatenate string2 onto the end of string1 strcmp(string1,string2); - 0 if string1 is equals to string2, < 0 if string1 is less than string2 >0 if string1 is greater than string2 strlen(string); - get the length of a string. strrev(string); - reverse the string and result is stored in same string.
  • 27. strcat() FUNCTION • The strcat function joins two strings together – SYNTAX: strcat(string1, string2); • string1 and string2 are character array • string2 is appended to string1 • The null character at the end of the string1 is removed and string2 is placed from there • The string2 remains unchanged
  • 28. Example #include <stdio.h> #include <string.h> int main () { char src[50], dest[50]; puts(“Enter a text1”); gets(src); puts(“nEnter a text2”); gets(dest); strcat(dest, src); printf("Final destination string : |%s|", dest); }
  • 29. C program to concatenate two strings without using strcat() #include<stdio.h> void main(void) { 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'; printf("nConcatenated String is %s",str1); }
  • 30. strcmp() FUNCTION • Compares two strings identified by the arguments and has a value 0 if they are equal • If they are not, it has the numeric difference between the first non-matching characters in the strings strcmp(string1, string2); – EXAMPLE: strcmp(nam1, name2); strcmp(name1, “John”); strcmp(“Rom”, “Ram”); strcmp(“their”, ”there”); • The above statement will return the value of -9 which is numeric difference between ASCII “i” and ASCII “r” is -9 • If the value is negative the string1 is alphabetically above string2
  • 31. #include <string.h> #include<conio.h> void main(void) { char str1[25],str2[25]; int dif,i=0; clrscr(); printf("nEnter the first String:"); gets(str1); printf("nEnter the secondString;"); gets(str2); while(str1[i]!='0'||str2[i]!='0') { dif=(str1[i]-str2[i]); if(dif!=0) break; i++; } if(dif>0) printf("%s comes after %s",str1,str2); else { if(dif<0) printf("%s comes after %s",str2,str1); else printf("both the strings are same"); } }
  • 32. C program to compare two strings using strcmp #include <stdio.h> #include <string.h> int main() { char a[100], b[100]; printf("Enter the first stringn"); gets(a); printf("Enter the second stringn"); gets(b); if( strcmp(a,b) == 0 ) printf("Entered strings are equal.n"); else printf("Entered strings are not equal.n"); }
  • 33. strcpy() FUNCITON • Works almost like a string-assignment operator – SYNTAX: strcpy(string1, string2); • Assigns the content of string2 to string1 – EXAMPLE: strcpy(city, “DELHI”); • Assign the string “DELHI” to the string variable city strcpy(city1, city2); • Assigns the contents of the string variable city2 to the string variable city1
  • 34. Copy String Manually without using strcpy() #include <stdio.h> int main() { char s1[100], s2[100], i; printf("Enter string s1: "); scanf("%s",s1); for(i=0; s1[i]!='0'; ++i) { s2[i]=s1[i]; } s2[i]='0'; printf("String s2: %s",s2); }
  • 35. strlen() FUNCTION • This function counts and return the number of characters in a string – SYNTAX: n = strlen(string); • Where n is the integer variable which receives the value of the length of the string • The counting ends at the first null character – EXAMPLE: Ch = “NEW YORK”; n = strlen(ch); printf(String Length = %dn”, n); – OUTPUT: String Length = 8
  • 36. TABLE OF STRINGS • We use lists of character strings, such as – List of name of students in a class – List of name of employees in an organization – List of places, etc • These list can be treated as a table of strings and a two dimensional array can be used to store the entire list – EXAMPLE: student[30][15]; • is an character array which can store a list of 30 names, each of length not more than 15 characters char city[ ][ ] = { “chandigarh”, “Madrad”, Ahmedab” };
  • 37. ARRAYS OF STRINGS • An array of strings is a two-dimensional array. The row index refers to a particular string, while the column index refers to a particular character within a string. Definition char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING]; Example char name[5][31];
  • 38. Initialization char identifier[NO_OF_STRINGS][MAX_NO_OF_BYTES_PER_STRING] = { "initializer 1", "initializer 2", ... }; For example, char name[5][31] = {“Logesh", "Jean", “ganesh", “moon", “kumaran”};
  • 39. Input and Output Input To accept input for a list of 5 names, we write char name[5][31]; for (i = 0; i < 5; i++) scanf(" %[^n]s", name[i]); The space in the format string skips leading whitespace before accepting the string. Output char name[5][31] = {"Harry", "Jean", "Jessica", "Irene", "Jim"}; printf("%s", name[2]);
  • 40. Sorting of string #include<stdio.h> int main(){ int i,j,n; char str[20][20],temp[20]; puts("Enter the no. of string to be sorted"); scanf("%d",&n); for(i=0;i<=n;i++) gets(str[i]); for(i=0;i<=n;i++) { for(j=i+1;j<=n;j++){ { if(strcmp(str[i],str[j])>0) { strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } } } printf("The sorted stringn"); for(i=0;i<=n;i++) puts(str[i]); }
  • 41. Search a name in a give list #include<stdio.h> #include<string.h> int main() { char name[5][10],found[10]; int j,i,flag=0; printf("Enter a name :"); for(i=0;i<5;i++) scanf("%s",name[i]); printf("enter a searching stringn"); scanf("%s",found); for(i=0;i<5;i++) { if(strcmp(name[i],found)==0) { flag=1; break; } } if(flag==1) printf("String foundn"); else printf("nString not found"); }