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

Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 
Implementation Of String Functions In C
Implementation Of String Functions In CImplementation Of String Functions In C
Implementation Of String Functions In CFazila Sadia
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Languagemadan reddy
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
String In C Language
String In C Language String In C Language
String In C Language Simplilearn
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programmingprogramming9
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C ProgrammingDevoAjit Gupta
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 

What's hot (20)

Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Strings
StringsStrings
Strings
 
String C Programming
String C ProgrammingString C Programming
String C Programming
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Implementation Of String Functions In C
Implementation Of String Functions In CImplementation Of String Functions In C
Implementation Of String Functions In C
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
C if else
C if elseC if else
C if else
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
String In C Language
String In C Language String In C Language
String In C Language
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
String c
String cString c
String c
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 

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 part2
Strings part2Strings part2
Strings part2
 
Strings in c++
Strings in c++Strings 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
 
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 (18)

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
 
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

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
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
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
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
 
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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Recently uploaded (20)

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
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
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
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...
 
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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

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.