SlideShare a Scribd company logo
1 of 29
String HandlingString Handling
inin
C ProgrammingC Programming
V.V. SubrahmanyamV.V. Subrahmanyam
SOCIS, IGNOUSOCIS, IGNOU
Date: 24-05-08Date: 24-05-08
Time: 12-00 to 12-45Time: 12-00 to 12-45
IntroductionIntroduction
 String can be represented as aString can be represented as a
single-dimensional charactersingle-dimensional character
type array.type array.
 C language does not provide theC language does not provide the
intrinsic string types.intrinsic string types.
 Some problems require that theSome problems require that the
characters within a string becharacters within a string be
processed individually.processed individually.
Contd…Contd…
 However, there are manyHowever, there are many
problems which require thatproblems which require that
strings be processed as completestrings be processed as complete
entities. Such problems can beentities. Such problems can be
manipulated considerablymanipulated considerably
through the use of special stringthrough the use of special string
oriented library functions.oriented library functions.
 The string functions operate onThe string functions operate on
null-terminated arrays ofnull-terminated arrays of
characters and require thecharacters and require the
header <string.h>.header <string.h>.
Characteristic Features of StringsCharacteristic Features of Strings
 Strings in C are group ofStrings in C are group of
characters, digits, and symbolscharacters, digits, and symbols
enclosed in quotation marks orenclosed in quotation marks or
simply we can say the string issimply we can say the string is
declared as a “character array”.declared as a “character array”.
 The end of the string is markedThe end of the string is marked
with a special character, the ‘0’with a special character, the ‘0’
((Null character)Null character), which has the, which has the
decimal value 0.decimal value 0.
Contd…Contd…
 There is a difference between aThere is a difference between a
charactercharacter stored in memory andstored in memory and
aa single character stringsingle character string storedstored
in a memory.in a memory.
 The character requires only oneThe character requires only one
byte whereas the singlebyte whereas the single
character string requires twocharacter string requires two
bytes (one byte for the characterbytes (one byte for the character
and other byte for the delimiter).and other byte for the delimiter).
Declaration of a StringDeclaration of a String
The syntax is:The syntax is:
char string-name[size];char string-name[size];
Examples:Examples:
char name[20];char name[20];
char address[25];char address[25];
char city[15];char city[15];
Initialization of StringsInitialization of Strings
char name[ 8] = {‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’, 0’};char name[ 8] = {‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’, 0’};
P R O G R A M 0
1001 1002 1005 1006 10071003 1004 1008
Array of StringsArray of Strings
 Array of strings are multipleArray of strings are multiple
strings, stored in the form ofstrings, stored in the form of
table. Declaring array of stringstable. Declaring array of strings
is same as strings, except it willis same as strings, except it will
have additional dimension tohave additional dimension to
store the number of strings.store the number of strings.
Syntax is as follows:Syntax is as follows:
char array-name[size][size];char array-name[size][size];
IllustrationIllustration
char names [3][10] = {“Rahul”, “Phani”, “Raj”};char names [3][10] = {“Rahul”, “Phani”, “Raj”};
0 1 2 3 4 5 6 7 8 9
R a h u l 0
P h a n i 00
R a j k u m a r 00
Sample ProgramSample Program
/* Program that initializes 3 names in an array of/* Program that initializes 3 names in an array of
strings and display them on to monitor.*/strings and display them on to monitor.*/
#include<stdio.h>#include<stdio.h>
#include<string.h>#include<string.h>
main()main()
{{
int n;int n;
char names[3][10] = {“Alex”, “Phillip”,char names[3][10] = {“Alex”, “Phillip”,
“Collins” };“Collins” };
for(n=0; n<3; n++)for(n=0; n<3; n++)
printf(“%sn”,names[n]);printf(“%sn”,names[n]);
}}
Built-in String FunctionsBuilt-in String Functions
Strlen FunctionStrlen Function
TheThe strlenstrlen function returns thefunction returns the
length of a string. It takes the stringlength of a string. It takes the string
name as argument. The syntax is asname as argument. The syntax is as
follows:follows:
n = strlen (str);n = strlen (str);
/* Program to illustrate the/* Program to illustrate the strlenstrlen function*/function*/
#include <stdio.h>#include <stdio.h>
#include <string.h>#include <string.h>
main()main()
{{
char name[80];char name[80];
int length;int length;
printf(“Enter your name: ”);printf(“Enter your name: ”);
gets(name);gets(name);
length = strlen(name);length = strlen(name);
printf(“Your name has %dprintf(“Your name has %d
charactersn”,length);charactersn”,length);
}}
Strcpy FunctionStrcpy Function
In C, you cannot simply assign oneIn C, you cannot simply assign one
character array to another. You havecharacter array to another. You have
to copy element by element. Theto copy element by element. The
strcpystrcpy function is used to copy onefunction is used to copy one
string to another.string to another.
The syntax is as follows:The syntax is as follows:
strcpy(str1, str2);strcpy(str1, str2);
/* Program to illustrate strcpy function*//* Program to illustrate strcpy function*/
#include <stdio.h>#include <stdio.h>
#include <string.h>#include <string.h>
main()main()
{{
char first[80], second[80];char first[80], second[80];
printf(“Enter a string: ”);printf(“Enter a string: ”);
gets(first);gets(first);
strcpy(second, first);strcpy(second, first);
printf(“n First string is : %s, and secondprintf(“n First string is : %s, and second
string is: %sn”, first,string is: %sn”, first,
second);second);
}}
Strcmp FunctionStrcmp Function
 TheThe strcmpstrcmp function compares twofunction compares two
strings, character by character andstrings, character by character and
stops comparison when there is astops comparison when there is a
difference in the ASCII value or thedifference in the ASCII value or the
end of any one string and returnsend of any one string and returns
ASCII difference of the charactersASCII difference of the characters
that is integer.that is integer.
 If the return valueIf the return value zerozero means themeans the
two strings are equal, a negativetwo strings are equal, a negative
value means that first is less thanvalue means that first is less than
second, and a positive value meanssecond, and a positive value means
first is greater than the second.first is greater than the second.
The syntax is:The syntax is:
n = strcmp(str1, str2);n = strcmp(str1, str2);
/* The following program uses the strcmp functions *//* The following program uses the strcmp functions */
#include <stdio.h>#include <stdio.h>
#include <string.h>#include <string.h>
main()main()
{{
char first[80], second[80];char first[80], second[80];
int value;int value;
printf(“Enter a string: ”);printf(“Enter a string: ”);
gets(first);gets(first);
printf(“Enter another string: ”);printf(“Enter another string: ”);
gets(second);gets(second);
value = strcmp(first,second);value = strcmp(first,second);
if(value == 0)if(value == 0)
puts(“The two strings are equaln”);puts(“The two strings are equaln”);
else if(value < 0)else if(value < 0)
puts(“The first string is smaller n”);puts(“The first string is smaller n”);
else if(value > 0)else if(value > 0)
puts(“the first string is biggern”);puts(“the first string is biggern”);
}}
Strcat FunctionStrcat Function
The strcat function is used to joinThe strcat function is used to join
one string to another. It takesone string to another. It takes
two strings as arguments; thetwo strings as arguments; the
characters of the second stringcharacters of the second string
will be appended to the firstwill be appended to the first
string. The syntax is:string. The syntax is:
strcat(str1, str2);strcat(str1, str2);
/* Program for string concatenation*//* Program for string concatenation*/
#include <stdio.h>#include <stdio.h>
#include <string.h>#include <string.h>
main()main()
{{
char first[80], second[80];char first[80], second[80];
printf(“Enter a string:”);printf(“Enter a string:”);
gets(first);gets(first);
printf(“Enter another string: ”);printf(“Enter another string: ”);
gets(second);gets(second);
strcat(first, second);strcat(first, second);
printf(“nThe two strings joined together:printf(“nThe two strings joined together:
%sn”, first);%sn”, first);
}}
Strlwr FunctionStrlwr Function
TheThe strlwrstrlwr function converts upperfunction converts upper
case characters of string to lowercase characters of string to lower
case characters.case characters.
The syntax is:The syntax is:
strlwr(str1);strlwr(str1);
/* Program that converts input string to/* Program that converts input string to
lower case characters */lower case characters */
#include <stdio.h>#include <stdio.h>
#include <string.h>#include <string.h>
main()main()
{{
char first[80];char first[80];
printf("Enter a string: ");printf("Enter a string: ");
gets(first);gets(first);
printf("Lower case of the string is %s”,printf("Lower case of the string is %s”,
strlwr(first));strlwr(first));
}}
Strrev FunctionStrrev Function
TheThe strrevstrrev funtion reverses thefuntion reverses the
given string.given string.
The syntax is:The syntax is:
strrev(str);strrev(str);
/* Program to reverse a given string *//* Program to reverse a given string */
#include <stdio.h>#include <stdio.h>
#include <string.h>#include <string.h>
main()main()
{{
char first[80];char first[80];
printf(“Enter a string:”);printf(“Enter a string:”);
gets(first);gets(first);
printf(“Reverse of the given string is :printf(“Reverse of the given string is :
%s ”,%s ”,
strrev(first));strrev(first));
}}
Strspn FunctionStrspn Function
TheThe strspnstrspn function returns thefunction returns the
position of the string, where firstposition of the string, where first
string mismatches with secondstring mismatches with second
string.string.
The syntax is:The syntax is:
n = strspn(first, second);n = strspn(first, second);
#include <stdio.h>#include <stdio.h>
#include <string.h>#include <string.h>
main()main()
{{
char first[80], second[80];char first[80], second[80];
printf("Enter first string: “);printf("Enter first string: “);
gets(first);gets(first);
printf(“n Enter second string: “);printf(“n Enter second string: “);
gets(second);gets(second);
printf(“n After %d characters there is noprintf(“n After %d characters there is no
match”,strspn(first, second));match”,strspn(first, second));
}}
OUTPUTOUTPUT
Enter first string: ALEXANDEREnter first string: ALEXANDER
Enter second string: ALEXSMITHEnter second string: ALEXSMITH
After 4 characters there is no matchAfter 4 characters there is no match
strncpy functionstrncpy function
TheThe strncpystrncpy function same asfunction same as strcpystrcpy. It. It
copies characters of one string to anothercopies characters of one string to another
string up to the specified length. Thestring up to the specified length. The
syntax is:syntax is:
strncpy(str1, str2, 10);strncpy(str1, str2, 10);
stricmp functionstricmp function
TheThe stricmpstricmp function is same asfunction is same as strcmpstrcmp,,
except it compares two strings ignoringexcept it compares two strings ignoring
the case (lower and upper case). Thethe case (lower and upper case). The
syntax is:syntax is:
n = stricmp(str1, str2);n = stricmp(str1, str2);
strncmp functionstrncmp function
TheThe strncmpstrncmp function is same asfunction is same as strcmpstrcmp,,
except it compares two strings up to aexcept it compares two strings up to a
specified length. The syntax is:specified length. The syntax is:
n = strncmp(str1, str2, 10);n = strncmp(str1, str2, 10);
strchr functionstrchr function
TheThe strchrstrchr funtion takes two argumentsfuntion takes two arguments
(the string and the character whose(the string and the character whose
address is to be specified) and returns theaddress is to be specified) and returns the
address of first occurrence of the characteraddress of first occurrence of the character
in the given string. The syntax is:in the given string. The syntax is:
cp = strchr (str, c);cp = strchr (str, c);
strset functionstrset function
TheThe strsetstrset funtion replaces the string with thefuntion replaces the string with the
given charactergiven character.. It takes two arguments theIt takes two arguments the
string and the character. The syntax is:string and the character. The syntax is:
strset (first, ch);strset (first, ch);
where stringwhere string firstfirst will be replaced by characterwill be replaced by character chch..
strncat functionstrncat function
The strncat function is the same asThe strncat function is the same as strcatstrcat, except, except
that it appends upto specified length. The syntaxthat it appends upto specified length. The syntax
is:is:
strncat(str1, str2,10);strncat(str1, str2,10);
where 10 characters of the str2 string is addedwhere 10 characters of the str2 string is added
into str1 string.into str1 string.
strupr functionstrupr function
The struprThe strupr functionfunction converts lower caseconverts lower case
characters of the string to upper casecharacters of the string to upper case
characters. The syntax is:characters. The syntax is:
strupr(str1);strupr(str1);
strstr functionstrstr function
TheThe strstrstrstr function takes two argumentsfunction takes two arguments
address of the string and second string asaddress of the string and second string as
inputs. And returns the address frominputs. And returns the address from
where the second string starts in the firstwhere the second string starts in the first
string. The syntax is:string. The syntax is:
cp = strstr (first, second);cp = strstr (first, second);
wherewhere firstfirst and sand secondecond are two strings,are two strings,
cpcp is character pointer.is character pointer.

More Related Content

What's hot

structure and union
structure and unionstructure and union
structure and unionstudent
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C ProgrammingDevoAjit Gupta
 
C programming - String
C programming - StringC programming - String
C programming - StringAchyut Devkota
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programmingAppili Vamsi Krishna
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programmingKamal Acharya
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - PointersWingston
 
datatypes and variables in c language
 datatypes and variables in c language datatypes and variables in c language
datatypes and variables in c languageRai University
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++Fahim Adil
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and outputOnline
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in CSahithi Naraparaju
 
String In C Language
String In C Language String In C Language
String In C Language Simplilearn
 

What's hot (20)

String C Programming
String C ProgrammingString C Programming
String C Programming
 
structure and union
structure and unionstructure and union
structure and union
 
Strings in C
Strings in CStrings in C
Strings in C
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
C programming - String
C programming - StringC programming - String
C programming - String
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
String c
String cString c
String c
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
String in c
String in cString in c
String in c
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
datatypes and variables in c language
 datatypes and variables in c language datatypes and variables in c language
datatypes and variables in c language
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
C++ string
C++ stringC++ string
C++ string
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
 
Pointers
PointersPointers
Pointers
 
String In C Language
String In C Language String In C Language
String In C Language
 

Similar to Strings in c (20)

Strings
StringsStrings
Strings
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
String notes
String notesString notes
String notes
 
C q 3
C q 3C q 3
C q 3
 
Strings
StringsStrings
Strings
 
Strings part2
Strings part2Strings part2
Strings part2
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Strings
StringsStrings
Strings
 
Strings
StringsStrings
Strings
 
Strings
StringsStrings
Strings
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPT
 
Team 1
Team 1Team 1
Team 1
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
String handling
String handlingString handling
String handling
 
string in C
string in Cstring in C
string in C
 
CP-STRING (1).ppt
CP-STRING (1).pptCP-STRING (1).ppt
CP-STRING (1).ppt
 

More from vampugani

Social media presentation
Social media presentationSocial media presentation
Social media presentationvampugani
 
Creating Quick Response(QR) Codes for the OER
Creating Quick Response(QR) Codes for the OERCreating Quick Response(QR) Codes for the OER
Creating Quick Response(QR) Codes for the OERvampugani
 
Arithmetic Computation using 2's Complement Notation
Arithmetic Computation using 2's Complement NotationArithmetic Computation using 2's Complement Notation
Arithmetic Computation using 2's Complement Notationvampugani
 
Post Graduate Diploma in Computer Applications (PGDCA)
Post Graduate Diploma in Computer Applications (PGDCA)Post Graduate Diploma in Computer Applications (PGDCA)
Post Graduate Diploma in Computer Applications (PGDCA)vampugani
 
Overview of Distributed Systems
Overview of Distributed SystemsOverview of Distributed Systems
Overview of Distributed Systemsvampugani
 
Protection and Security in Operating Systems
Protection and Security in Operating SystemsProtection and Security in Operating Systems
Protection and Security in Operating Systemsvampugani
 
Virtual Memory
Virtual MemoryVirtual Memory
Virtual Memoryvampugani
 
Memory Management in OS
Memory Management in OSMemory Management in OS
Memory Management in OSvampugani
 
Process Scheduling
Process SchedulingProcess Scheduling
Process Schedulingvampugani
 
Introduction to OS
Introduction to OSIntroduction to OS
Introduction to OSvampugani
 
Operating Systems
Operating SystemsOperating Systems
Operating Systemsvampugani
 
Distributed Systems
Distributed SystemsDistributed Systems
Distributed Systemsvampugani
 
Multiprocessor Systems
Multiprocessor SystemsMultiprocessor Systems
Multiprocessor Systemsvampugani
 
File Management in Operating Systems
File Management in Operating SystemsFile Management in Operating Systems
File Management in Operating Systemsvampugani
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in cvampugani
 
Introduction to C Programming
Introduction to C Programming Introduction to C Programming
Introduction to C Programming vampugani
 
Introduction to C Programming - I
Introduction to C Programming - I Introduction to C Programming - I
Introduction to C Programming - I vampugani
 

More from vampugani (19)

Social media presentation
Social media presentationSocial media presentation
Social media presentation
 
Creating Quick Response(QR) Codes for the OER
Creating Quick Response(QR) Codes for the OERCreating Quick Response(QR) Codes for the OER
Creating Quick Response(QR) Codes for the OER
 
Arithmetic Computation using 2's Complement Notation
Arithmetic Computation using 2's Complement NotationArithmetic Computation using 2's Complement Notation
Arithmetic Computation using 2's Complement Notation
 
Post Graduate Diploma in Computer Applications (PGDCA)
Post Graduate Diploma in Computer Applications (PGDCA)Post Graduate Diploma in Computer Applications (PGDCA)
Post Graduate Diploma in Computer Applications (PGDCA)
 
Overview of Distributed Systems
Overview of Distributed SystemsOverview of Distributed Systems
Overview of Distributed Systems
 
Protection and Security in Operating Systems
Protection and Security in Operating SystemsProtection and Security in Operating Systems
Protection and Security in Operating Systems
 
Virtual Memory
Virtual MemoryVirtual Memory
Virtual Memory
 
Memory Management in OS
Memory Management in OSMemory Management in OS
Memory Management in OS
 
Process Scheduling
Process SchedulingProcess Scheduling
Process Scheduling
 
Processes
ProcessesProcesses
Processes
 
Introduction to OS
Introduction to OSIntroduction to OS
Introduction to OS
 
Operating Systems
Operating SystemsOperating Systems
Operating Systems
 
Distributed Systems
Distributed SystemsDistributed Systems
Distributed Systems
 
Multiprocessor Systems
Multiprocessor SystemsMultiprocessor Systems
Multiprocessor Systems
 
File Management in Operating Systems
File Management in Operating SystemsFile Management in Operating Systems
File Management in Operating Systems
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in c
 
Introduction to C Programming
Introduction to C Programming Introduction to C Programming
Introduction to C Programming
 
Introduction to C Programming - I
Introduction to C Programming - I Introduction to C Programming - I
Introduction to C Programming - I
 

Recently uploaded

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Recently uploaded (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Strings in c

  • 1. String HandlingString Handling inin C ProgrammingC Programming V.V. SubrahmanyamV.V. Subrahmanyam SOCIS, IGNOUSOCIS, IGNOU Date: 24-05-08Date: 24-05-08 Time: 12-00 to 12-45Time: 12-00 to 12-45
  • 2. IntroductionIntroduction  String can be represented as aString can be represented as a single-dimensional charactersingle-dimensional character type array.type array.  C language does not provide theC language does not provide the intrinsic string types.intrinsic string types.  Some problems require that theSome problems require that the characters within a string becharacters within a string be processed individually.processed individually.
  • 3. Contd…Contd…  However, there are manyHowever, there are many problems which require thatproblems which require that strings be processed as completestrings be processed as complete entities. Such problems can beentities. Such problems can be manipulated considerablymanipulated considerably through the use of special stringthrough the use of special string oriented library functions.oriented library functions.  The string functions operate onThe string functions operate on null-terminated arrays ofnull-terminated arrays of characters and require thecharacters and require the header <string.h>.header <string.h>.
  • 4. Characteristic Features of StringsCharacteristic Features of Strings  Strings in C are group ofStrings in C are group of characters, digits, and symbolscharacters, digits, and symbols enclosed in quotation marks orenclosed in quotation marks or simply we can say the string issimply we can say the string is declared as a “character array”.declared as a “character array”.  The end of the string is markedThe end of the string is marked with a special character, the ‘0’with a special character, the ‘0’ ((Null character)Null character), which has the, which has the decimal value 0.decimal value 0.
  • 5. Contd…Contd…  There is a difference between aThere is a difference between a charactercharacter stored in memory andstored in memory and aa single character stringsingle character string storedstored in a memory.in a memory.  The character requires only oneThe character requires only one byte whereas the singlebyte whereas the single character string requires twocharacter string requires two bytes (one byte for the characterbytes (one byte for the character and other byte for the delimiter).and other byte for the delimiter).
  • 6. Declaration of a StringDeclaration of a String The syntax is:The syntax is: char string-name[size];char string-name[size]; Examples:Examples: char name[20];char name[20]; char address[25];char address[25]; char city[15];char city[15];
  • 7. Initialization of StringsInitialization of Strings char name[ 8] = {‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’, 0’};char name[ 8] = {‘P’, ‘R’, ‘O’, ‘G’, ‘R’, ‘A’, ‘M’, 0’}; P R O G R A M 0 1001 1002 1005 1006 10071003 1004 1008
  • 8. Array of StringsArray of Strings  Array of strings are multipleArray of strings are multiple strings, stored in the form ofstrings, stored in the form of table. Declaring array of stringstable. Declaring array of strings is same as strings, except it willis same as strings, except it will have additional dimension tohave additional dimension to store the number of strings.store the number of strings. Syntax is as follows:Syntax is as follows: char array-name[size][size];char array-name[size][size];
  • 9. IllustrationIllustration char names [3][10] = {“Rahul”, “Phani”, “Raj”};char names [3][10] = {“Rahul”, “Phani”, “Raj”}; 0 1 2 3 4 5 6 7 8 9 R a h u l 0 P h a n i 00 R a j k u m a r 00
  • 10. Sample ProgramSample Program /* Program that initializes 3 names in an array of/* Program that initializes 3 names in an array of strings and display them on to monitor.*/strings and display them on to monitor.*/ #include<stdio.h>#include<stdio.h> #include<string.h>#include<string.h> main()main() {{ int n;int n; char names[3][10] = {“Alex”, “Phillip”,char names[3][10] = {“Alex”, “Phillip”, “Collins” };“Collins” }; for(n=0; n<3; n++)for(n=0; n<3; n++) printf(“%sn”,names[n]);printf(“%sn”,names[n]); }}
  • 11. Built-in String FunctionsBuilt-in String Functions Strlen FunctionStrlen Function TheThe strlenstrlen function returns thefunction returns the length of a string. It takes the stringlength of a string. It takes the string name as argument. The syntax is asname as argument. The syntax is as follows:follows: n = strlen (str);n = strlen (str);
  • 12. /* Program to illustrate the/* Program to illustrate the strlenstrlen function*/function*/ #include <stdio.h>#include <stdio.h> #include <string.h>#include <string.h> main()main() {{ char name[80];char name[80]; int length;int length; printf(“Enter your name: ”);printf(“Enter your name: ”); gets(name);gets(name); length = strlen(name);length = strlen(name); printf(“Your name has %dprintf(“Your name has %d charactersn”,length);charactersn”,length); }}
  • 13. Strcpy FunctionStrcpy Function In C, you cannot simply assign oneIn C, you cannot simply assign one character array to another. You havecharacter array to another. You have to copy element by element. Theto copy element by element. The strcpystrcpy function is used to copy onefunction is used to copy one string to another.string to another. The syntax is as follows:The syntax is as follows: strcpy(str1, str2);strcpy(str1, str2);
  • 14. /* Program to illustrate strcpy function*//* Program to illustrate strcpy function*/ #include <stdio.h>#include <stdio.h> #include <string.h>#include <string.h> main()main() {{ char first[80], second[80];char first[80], second[80]; printf(“Enter a string: ”);printf(“Enter a string: ”); gets(first);gets(first); strcpy(second, first);strcpy(second, first); printf(“n First string is : %s, and secondprintf(“n First string is : %s, and second string is: %sn”, first,string is: %sn”, first, second);second); }}
  • 15. Strcmp FunctionStrcmp Function  TheThe strcmpstrcmp function compares twofunction compares two strings, character by character andstrings, character by character and stops comparison when there is astops comparison when there is a difference in the ASCII value or thedifference in the ASCII value or the end of any one string and returnsend of any one string and returns ASCII difference of the charactersASCII difference of the characters that is integer.that is integer.  If the return valueIf the return value zerozero means themeans the two strings are equal, a negativetwo strings are equal, a negative value means that first is less thanvalue means that first is less than second, and a positive value meanssecond, and a positive value means first is greater than the second.first is greater than the second.
  • 16. The syntax is:The syntax is: n = strcmp(str1, str2);n = strcmp(str1, str2);
  • 17. /* The following program uses the strcmp functions *//* The following program uses the strcmp functions */ #include <stdio.h>#include <stdio.h> #include <string.h>#include <string.h> main()main() {{ char first[80], second[80];char first[80], second[80]; int value;int value; printf(“Enter a string: ”);printf(“Enter a string: ”); gets(first);gets(first); printf(“Enter another string: ”);printf(“Enter another string: ”); gets(second);gets(second); value = strcmp(first,second);value = strcmp(first,second); if(value == 0)if(value == 0) puts(“The two strings are equaln”);puts(“The two strings are equaln”); else if(value < 0)else if(value < 0) puts(“The first string is smaller n”);puts(“The first string is smaller n”); else if(value > 0)else if(value > 0) puts(“the first string is biggern”);puts(“the first string is biggern”); }}
  • 18. Strcat FunctionStrcat Function The strcat function is used to joinThe strcat function is used to join one string to another. It takesone string to another. It takes two strings as arguments; thetwo strings as arguments; the characters of the second stringcharacters of the second string will be appended to the firstwill be appended to the first string. The syntax is:string. The syntax is: strcat(str1, str2);strcat(str1, str2);
  • 19. /* Program for string concatenation*//* Program for string concatenation*/ #include <stdio.h>#include <stdio.h> #include <string.h>#include <string.h> main()main() {{ char first[80], second[80];char first[80], second[80]; printf(“Enter a string:”);printf(“Enter a string:”); gets(first);gets(first); printf(“Enter another string: ”);printf(“Enter another string: ”); gets(second);gets(second); strcat(first, second);strcat(first, second); printf(“nThe two strings joined together:printf(“nThe two strings joined together: %sn”, first);%sn”, first); }}
  • 20. Strlwr FunctionStrlwr Function TheThe strlwrstrlwr function converts upperfunction converts upper case characters of string to lowercase characters of string to lower case characters.case characters. The syntax is:The syntax is: strlwr(str1);strlwr(str1);
  • 21. /* Program that converts input string to/* Program that converts input string to lower case characters */lower case characters */ #include <stdio.h>#include <stdio.h> #include <string.h>#include <string.h> main()main() {{ char first[80];char first[80]; printf("Enter a string: ");printf("Enter a string: "); gets(first);gets(first); printf("Lower case of the string is %s”,printf("Lower case of the string is %s”, strlwr(first));strlwr(first)); }}
  • 22. Strrev FunctionStrrev Function TheThe strrevstrrev funtion reverses thefuntion reverses the given string.given string. The syntax is:The syntax is: strrev(str);strrev(str);
  • 23. /* Program to reverse a given string *//* Program to reverse a given string */ #include <stdio.h>#include <stdio.h> #include <string.h>#include <string.h> main()main() {{ char first[80];char first[80]; printf(“Enter a string:”);printf(“Enter a string:”); gets(first);gets(first); printf(“Reverse of the given string is :printf(“Reverse of the given string is : %s ”,%s ”, strrev(first));strrev(first)); }}
  • 24. Strspn FunctionStrspn Function TheThe strspnstrspn function returns thefunction returns the position of the string, where firstposition of the string, where first string mismatches with secondstring mismatches with second string.string. The syntax is:The syntax is: n = strspn(first, second);n = strspn(first, second);
  • 25. #include <stdio.h>#include <stdio.h> #include <string.h>#include <string.h> main()main() {{ char first[80], second[80];char first[80], second[80]; printf("Enter first string: “);printf("Enter first string: “); gets(first);gets(first); printf(“n Enter second string: “);printf(“n Enter second string: “); gets(second);gets(second); printf(“n After %d characters there is noprintf(“n After %d characters there is no match”,strspn(first, second));match”,strspn(first, second)); }} OUTPUTOUTPUT Enter first string: ALEXANDEREnter first string: ALEXANDER Enter second string: ALEXSMITHEnter second string: ALEXSMITH After 4 characters there is no matchAfter 4 characters there is no match
  • 26. strncpy functionstrncpy function TheThe strncpystrncpy function same asfunction same as strcpystrcpy. It. It copies characters of one string to anothercopies characters of one string to another string up to the specified length. Thestring up to the specified length. The syntax is:syntax is: strncpy(str1, str2, 10);strncpy(str1, str2, 10); stricmp functionstricmp function TheThe stricmpstricmp function is same asfunction is same as strcmpstrcmp,, except it compares two strings ignoringexcept it compares two strings ignoring the case (lower and upper case). Thethe case (lower and upper case). The syntax is:syntax is: n = stricmp(str1, str2);n = stricmp(str1, str2);
  • 27. strncmp functionstrncmp function TheThe strncmpstrncmp function is same asfunction is same as strcmpstrcmp,, except it compares two strings up to aexcept it compares two strings up to a specified length. The syntax is:specified length. The syntax is: n = strncmp(str1, str2, 10);n = strncmp(str1, str2, 10); strchr functionstrchr function TheThe strchrstrchr funtion takes two argumentsfuntion takes two arguments (the string and the character whose(the string and the character whose address is to be specified) and returns theaddress is to be specified) and returns the address of first occurrence of the characteraddress of first occurrence of the character in the given string. The syntax is:in the given string. The syntax is: cp = strchr (str, c);cp = strchr (str, c);
  • 28. strset functionstrset function TheThe strsetstrset funtion replaces the string with thefuntion replaces the string with the given charactergiven character.. It takes two arguments theIt takes two arguments the string and the character. The syntax is:string and the character. The syntax is: strset (first, ch);strset (first, ch); where stringwhere string firstfirst will be replaced by characterwill be replaced by character chch.. strncat functionstrncat function The strncat function is the same asThe strncat function is the same as strcatstrcat, except, except that it appends upto specified length. The syntaxthat it appends upto specified length. The syntax is:is: strncat(str1, str2,10);strncat(str1, str2,10); where 10 characters of the str2 string is addedwhere 10 characters of the str2 string is added into str1 string.into str1 string.
  • 29. strupr functionstrupr function The struprThe strupr functionfunction converts lower caseconverts lower case characters of the string to upper casecharacters of the string to upper case characters. The syntax is:characters. The syntax is: strupr(str1);strupr(str1); strstr functionstrstr function TheThe strstrstrstr function takes two argumentsfunction takes two arguments address of the string and second string asaddress of the string and second string as inputs. And returns the address frominputs. And returns the address from where the second string starts in the firstwhere the second string starts in the first string. The syntax is:string. The syntax is: cp = strstr (first, second);cp = strstr (first, second); wherewhere firstfirst and sand secondecond are two strings,are two strings, cpcp is character pointer.is character pointer.