SlideShare una empresa de Scribd logo
1 de 21
Strings
08/23/151
Strings
The string in C programming language is actually a one-
dimensional array of characters which is terminated by
a null character '0'. 
Since stringstring is an array, the declaration of a string is the same as
declaring a char array.
char string1[30];
char str2[20] = “Initial value”;
The following declaration and initialization create a string consisting
of the word "Hello". To hold the null character at the end of the
array, the size of the character array containing the string is one
more than the number of characters in the word "Hello."
08/23/152
Declaration and Initialization of
Strings
 The following declaration and initialization create a string consisting of the word "Hello".
 To hold the null character at the end of the array, the size of the character array containing
the string is one more than the number of characters in the word “Hello.”
 char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
 Another way of Initialization is (shortcut for initializing string)
 char greeting[] = "Hello";
 Note: We did not place the null character at the end of a string constant. The C compiler
automatically places the '0' at the end of the string when it initializes the array.
 Each character in the array occupies one byte of memory and the last character is always
‘0’.
 It looks like two characters, but it is actually only one character, with the  indicating that
what follows it is something special.
 ‘0’ is called null character.
 Note that ‘0’ and ‘0’ are not same. ASCII value of ‘0’ is 0, whereas ASCII value of ‘0’ is
48.
08/23/153
Importance of ‘0’ (null
character )
The terminating null (‘0’) is important, because it is the only way the
functions that work with a string can know where the string ends.
In fact, a string not terminated by a ‘0’ is not really a string,
but merely a collection of characters.
Memory Representation of String:
char greeting[] = "Hello";
08/23/154
Address 5000 5001 5002 5003 5004 5005
Printing String
/* Program to demonstrate printing of a string */
main( )
{
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( i <= 7 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
And here is the output...
Klinsman
08/23/155
Printing String
• Can we write the while loop without using the final value 7?
• Yes:We can; because we know that each character array always ends with a
‘0’.
Following program illustrates this.
main( )
{
char name[ ] = "Klinsman" ;
int i = 0 ;
while ( name[i] != ‘0’ )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
And here is the output...
Klinsman
Note: This program doesn’t depend on the length of the string.
08/23/156
Using %s format specifier
 printf( ) function has got a sweet and simple way of printing string, as shown below.
Note that printf( ) doesn’t print the ‘0’.
main( )
{
char name[ ] = "Klinsman" ;
printf ( "%s", name ) ;
}
 The %s used in printf( ) is a format specification for printing out a string.
 %s can be used to receive a string from the keyboard, as shown below.
main( )
{
char name[25] ;
printf ( "Enter your name: " ) ;
scanf ( "%s", name ) ;
printf ( "Hello %s!", name ) ;
}
Note: Once you hit the enter key, scanf( ) places a ‘0’ in the array.
08/23/157
Sample output:
Enter your name: Pratik
Hello Pratik!
Some Notable points
 While entering the string using scanf( ) we must be cautious about two things:
(a) The length of the string should not exceed the dimension of the character array. This is
because the C compiler doesn’t perform bounds checking on character arrays. Hence, if you
carelessly exceed the bounds there is always a danger of overwriting something important.
(b) scanf( ) is not capable of receiving multi-word strings.Therefore names such as ‘Pratik
Kumar’ would be unacceptable.
The way to get around this limitation is by using the function gets( ).
• The usage of functions gets( ) and its counterpart puts( ) is shown below.
main( )
{
char name[25] ;
printf ( "Enter your full name: " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
}
08/23/158
And here is the output...
Enter your full name: Pratik Kumar
Hello!
Pratik Kumar
How to receive multi-word string using
scanf()
If we are prepared to take the trouble we can make scanf( )
accept multi-word strings by writing it in this manner:
char name[25] ;
printf ( "Enter your full name " ) ;
scanf ( "%[^n]s", name ) ;
08/23/159
Standard Library String
Functions
With every C compiler a large set of useful string handling
library functions are provided.
For Using following library function we need to include the
headerfile string.h
08/23/1510
Function Use
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strcpy Copies a string into another
strcmp Compares two strings
strchr Finds first occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string
Cont…
Out of the above list we shall discuss the functions strlen( ),
strcpy( ), strcat( ) and strcmp( ), since these are the most
commonly used functions.
strlen( ):This function counts the number of characters present
in a string.
main( )
{
char arr[ ] = “Herry" ;
int len1, len2 ;
len1 = strlen ( arr ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "nstring = %s length = %d", arr, len1 ) ;
printf ( "nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
}
 Note: While calculating the length it doesn’t count ‘0’. 08/23/1511
O/P:
string = Herry length = 5
string = Humpty Dumpty length = 13
Writing own function xstrlen( ) which
imitates strlen( )
int xstrlen ( char s[] )
{
int length = 0,i=0 ;
while ( s[i] != '0' )
{
length++ ;
i++ ;
}
return ( length ) ;
}
08/23/1512
More efficient xstrlen
int xstrlen ( char s[] )
{
int i ;
for(i=0; s[i] != '0' ;i++);
return ( i ) ;
}
strcpy( )
This function copies the contents of one string into another.
The base addresses of the source and target strings should be supplied
to this function.
Example of strcpy( )
void main()
{
char source[ ] = "Sayonara" ;
char target[20] ;
strcpy ( target, source ) ;
printf ( "nsource string = %s", source ) ;
printf ( "ntarget string = %s", target ) ;
}
 Note:It is our responsibility to see to it that the target string’s dimension is big
enough to hold the string being copied into it.
08/23/1513
And here is the output...
source string = Sayonara
target string = Sayonara
Implementing strcpy function
void xstrcpy ( char t[], char s[] )
{ int i;
for ( i=0;s[i] != ‘0’ ; i++ )
{
t[i] = s[i] ;
}
t [i]= '0' ;
printf ( "nsource string = %s", s ) ;
printf ( "ntarget string = %s", t ) ;
}
void main()
{
char source[ ] = "Sayonara" ;
char target[20] ;
xstrcpy ( target, source ) ;
}
08/23/1514
And here is the output...
source string = Sayonara
target string = Sayonara
strcat( )
 This function concatenates the source string at the end of the target string.
 For example, “Bombay” and “Nagpur” on concatenation would result into a string
“BombayNagpur”.
 Here is an example of strcat( )
main( )
{
char source[ ] = "Folks!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "nsource string = %s", source ) ;
printf ( "ntarget string = %s", target ) ;
}
08/23/1515
And here is the output...
source string = Folks!
target string = HelloFolks!
strcmp( )
 This is a function which compares two strings to find out whether they are same or
different.
 The two strings are compared character by character until there is a mismatch or end
of one of the strings is reached, whichever occurs first.
 If the two strings are identical, strcmp( ) returns a value zero.
 If they’re not identical, it returns the numeric difference between the ASCII values of
the first non-matching pairs of characters.
 Example
main( ){
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "n%d %d %d", i, j, k ) ;
}
08/23/1516
And here is the output...
0 4 -32
Cont…
In the first call to strcmp( ), the two strings are identical—“Jerry”
and “Jerry”—and the value returned by strcmp( ) is zero.
In the second call, the first character of “Jerry” doesn't match with
the first character of “Ferry” and the result is 4, which is the numeric
difference between ASCII value of ‘J’ and ASCII value of ‘F’.
In the third call to strcmp( ) “Jerry” doesn’t match with “Jerry boy”,
because the null character at the end of “Jerry” doesn’t match the
blank in “Jerry boy”. The value returned is -32, which is the value of
null character minus the ASCII value of space, i.e., ‘0’ minus ‘ ’,
which is equal to -32.
Note: The exact value of mismatch will rarely concern us. Any non-
zero value means there is a mismatch.
08/23/1517
Homework
Write the programms to implement the strcat and strcmp
functions.
void main(void) {
char str1[25],str2[25];
int i,j;
printf("nEnter First String:");
gets(str1);
printf("nEnter Second String:");
gets(str2);
for(i=0;str1[i]!=‘0’; i++) ;
for(j=0; str2[j]!=‘0’; j++, i++)
str1[i]=str2[j];
str1[i]='0';
printf("nConcatenated String is %s",str1);
}
08/23/1518
Program to compare two string
#include<stdio.h>
int compare(char a[], char b[]){
int c = 0;
while( a[c] == b[c] ){
if( a[c] == '0' || b[c] == '0' )
break;
c++;
}
if( a[c] == '0' && b[c] == '0' )
return 0;
else
return (a[c] - b[c]);
}
08/23/1519
void main(void) {
char str1[25],str2[25];
printf("nEnter First String:");
gets(str1);
printf("nEnter Second
String:");
gets(str2);
int l= compare(str1,str2);
if(l==0)
printf("nsame=%d",l);
else
printf("nnot same=%d",l);
}
Characters
#define FOUND 1
#define NOTFOUND 0
main( )
{
char masterlist[6][40], yourname[40] ;
int i, a, flag= NOTFOUND ;
printf ( "nEnter MASTERLIST" ) ;
for ( i = 0 ; i <= 5 ; i++ )
gets( &masterlist[i][0] ) ;
printf ( "nEnter your name " ) ;
gets(yourname ) ;
for ( i = 0 ; i <= 5 ; i++ ){
a = strcmp ( &masterlist[i][0], yourname ) ;
if ( a == 0 ){
printf ( "Welcome, you can enter into LT2" ) ;
flag = FOUND ;
break ;
}
}
if ( flag == NOTFOUND )
printf ( "Sorry, you can not enter!" ) ;
}
08/23/1520
Notable Points
 The order of the subscripts in the array declaration is important. The first subscript
gives the number of names in the array, while the second subscript gives the length of
each item in the array.
 While comparing the strings through strcmp( ), note that the addresses of the
strings are being passed to strcmp( ). As seen in the last lecture, if the two strings
match, strcmp( ) would return a value 0, otherwise it would return a non-zero
value.
 char masterlist[6][10] will be stored in memory as shown in Fig.
 Note that each string ends with a ‘0’.
 Here, 65454, 65464, 65474, etc. are the base addresses of successive names.
08/23/1521

Más contenido relacionado

La actualidad más candente (20)

Strings in c++
Strings in c++Strings in c++
Strings in c++
 
String in programming language in c or c++
 String in programming language  in c or c++  String in programming language  in c or c++
String in programming language in c or c++
 
Strings
StringsStrings
Strings
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
C string
C stringC string
C string
 
Strings in C
Strings in CStrings in C
Strings in C
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
String c
String cString c
String c
 
Strings in C
Strings in CStrings in C
Strings in C
 
String in c programming
String in c programmingString in c programming
String in c programming
 
C programming - String
C programming - StringC programming - String
C programming - String
 
String C Programming
String C ProgrammingString C Programming
String C Programming
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
string in C
string in Cstring in C
string in C
 
Strings
StringsStrings
Strings
 
strings
stringsstrings
strings
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
 
Strings
StringsStrings
Strings
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
 

Similar a 14 strings

C Programming Strings.docx
C Programming Strings.docxC Programming Strings.docx
C Programming Strings.docx8759000398
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programmingmikeymanjiro2090
 
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.pdfSowmyaJyothi3
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxJStalinAsstProfessor
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string libraryMomenMostafa
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11Rumman Ansari
 
Data structure week 3
Data structure week 3Data structure week 3
Data structure week 3karmuhtam
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++Azeemaj101
 
Strings in programming tutorial.
Strings  in programming tutorial.Strings  in programming tutorial.
Strings in programming tutorial.Samsil Arefin
 

Similar a 14 strings (20)

[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++
 
C Programming Strings.docx
C Programming Strings.docxC Programming Strings.docx
C Programming Strings.docx
 
String notes
String notesString notes
String notes
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
 
Unitii string
Unitii stringUnitii string
Unitii string
 
CP-STRING (1).ppt
CP-STRING (1).pptCP-STRING (1).ppt
CP-STRING (1).ppt
 
CP-STRING.ppt
CP-STRING.pptCP-STRING.ppt
CP-STRING.ppt
 
CP-STRING.ppt
CP-STRING.pptCP-STRING.ppt
CP-STRING.ppt
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
c programming
c programmingc programming
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
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
 
Data structure week 3
Data structure week 3Data structure week 3
Data structure week 3
 
Unit 2
Unit 2Unit 2
Unit 2
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++
 
Strings in programming tutorial.
Strings  in programming tutorial.Strings  in programming tutorial.
Strings in programming tutorial.
 

Más de Rohit Shrivastava (13)

1 introduction-to-computer
1 introduction-to-computer1 introduction-to-computer
1 introduction-to-computer
 
17 structure-and-union
17 structure-and-union17 structure-and-union
17 structure-and-union
 
16 dynamic-memory-allocation
16 dynamic-memory-allocation16 dynamic-memory-allocation
16 dynamic-memory-allocation
 
11 functions
11 functions11 functions
11 functions
 
10 array
10 array10 array
10 array
 
8 number-system
8 number-system8 number-system
8 number-system
 
7 decision-control
7 decision-control7 decision-control
7 decision-control
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
 
3 algorithm-and-flowchart
3 algorithm-and-flowchart3 algorithm-and-flowchart
3 algorithm-and-flowchart
 
2 memory-and-io-devices
2 memory-and-io-devices2 memory-and-io-devices
2 memory-and-io-devices
 
4 evolution-of-programming-languages
4 evolution-of-programming-languages4 evolution-of-programming-languages
4 evolution-of-programming-languages
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 

Último

History and Development of Pharmacovigilence.pdf
History and Development of Pharmacovigilence.pdfHistory and Development of Pharmacovigilence.pdf
History and Development of Pharmacovigilence.pdfSasikiranMarri
 
call girls in Dwarka Sector 21 Metro DELHI 🔝 >༒9540349809 🔝 genuine Escort Se...
call girls in Dwarka Sector 21 Metro DELHI 🔝 >༒9540349809 🔝 genuine Escort Se...call girls in Dwarka Sector 21 Metro DELHI 🔝 >༒9540349809 🔝 genuine Escort Se...
call girls in Dwarka Sector 21 Metro DELHI 🔝 >༒9540349809 🔝 genuine Escort Se...saminamagar
 
Case Report Peripartum Cardiomyopathy.pptx
Case Report Peripartum Cardiomyopathy.pptxCase Report Peripartum Cardiomyopathy.pptx
Case Report Peripartum Cardiomyopathy.pptxNiranjan Chavan
 
POST NATAL EXERCISES AND ITS IMPACT.pptx
POST NATAL EXERCISES AND ITS IMPACT.pptxPOST NATAL EXERCISES AND ITS IMPACT.pptx
POST NATAL EXERCISES AND ITS IMPACT.pptxvirengeeta
 
Glomerular Filtration rate and its determinants.pptx
Glomerular Filtration rate and its determinants.pptxGlomerular Filtration rate and its determinants.pptx
Glomerular Filtration rate and its determinants.pptxDr.Nusrat Tariq
 
97111 47426 Call Girls In Delhi MUNIRKAA
97111 47426 Call Girls In Delhi MUNIRKAA97111 47426 Call Girls In Delhi MUNIRKAA
97111 47426 Call Girls In Delhi MUNIRKAAjennyeacort
 
call girls in green park DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in green park  DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️call girls in green park  DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in green park DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️saminamagar
 
world health day presentation ppt download
world health day presentation ppt downloadworld health day presentation ppt download
world health day presentation ppt downloadAnkitKumar311566
 
call girls in paharganj DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in paharganj DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️call girls in paharganj DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in paharganj DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️saminamagar
 
call girls in aerocity DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in aerocity DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️call girls in aerocity DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in aerocity DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️saminamagar
 
Presentation on Parasympathetic Nervous System
Presentation on Parasympathetic Nervous SystemPresentation on Parasympathetic Nervous System
Presentation on Parasympathetic Nervous SystemPrerana Jadhav
 
Presentació "Real-Life VR Integration for Mild Cognitive Impairment Rehabilit...
Presentació "Real-Life VR Integration for Mild Cognitive Impairment Rehabilit...Presentació "Real-Life VR Integration for Mild Cognitive Impairment Rehabilit...
Presentació "Real-Life VR Integration for Mild Cognitive Impairment Rehabilit...Badalona Serveis Assistencials
 
PULMONARY EMBOLISM AND ITS MANAGEMENTS.pdf
PULMONARY EMBOLISM AND ITS MANAGEMENTS.pdfPULMONARY EMBOLISM AND ITS MANAGEMENTS.pdf
PULMONARY EMBOLISM AND ITS MANAGEMENTS.pdfDolisha Warbi
 
Presentation on General Anesthetics pdf.
Presentation on General Anesthetics pdf.Presentation on General Anesthetics pdf.
Presentation on General Anesthetics pdf.Prerana Jadhav
 
Apiculture Chapter 1. Introduction 2.ppt
Apiculture Chapter 1. Introduction 2.pptApiculture Chapter 1. Introduction 2.ppt
Apiculture Chapter 1. Introduction 2.pptkedirjemalharun
 
Music Therapy's Impact in Palliative Care| IAPCON2024| Dr. Tara Rajendran
Music Therapy's Impact in Palliative Care| IAPCON2024| Dr. Tara RajendranMusic Therapy's Impact in Palliative Care| IAPCON2024| Dr. Tara Rajendran
Music Therapy's Impact in Palliative Care| IAPCON2024| Dr. Tara RajendranTara Rajendran
 
Big Data Analysis Suggests COVID Vaccination Increases Excess Mortality Of ...
Big Data Analysis Suggests COVID  Vaccination Increases Excess Mortality Of  ...Big Data Analysis Suggests COVID  Vaccination Increases Excess Mortality Of  ...
Big Data Analysis Suggests COVID Vaccination Increases Excess Mortality Of ...sdateam0
 
epilepsy and status epilepticus for undergraduate.pptx
epilepsy and status epilepticus  for undergraduate.pptxepilepsy and status epilepticus  for undergraduate.pptx
epilepsy and status epilepticus for undergraduate.pptxMohamed Rizk Khodair
 
Measurement of Radiation and Dosimetric Procedure.pptx
Measurement of Radiation and Dosimetric Procedure.pptxMeasurement of Radiation and Dosimetric Procedure.pptx
Measurement of Radiation and Dosimetric Procedure.pptxDr. Dheeraj Kumar
 
VarSeq 2.6.0: Advancing Pharmacogenomics and Genomic Analysis
VarSeq 2.6.0: Advancing Pharmacogenomics and Genomic AnalysisVarSeq 2.6.0: Advancing Pharmacogenomics and Genomic Analysis
VarSeq 2.6.0: Advancing Pharmacogenomics and Genomic AnalysisGolden Helix
 

Último (20)

History and Development of Pharmacovigilence.pdf
History and Development of Pharmacovigilence.pdfHistory and Development of Pharmacovigilence.pdf
History and Development of Pharmacovigilence.pdf
 
call girls in Dwarka Sector 21 Metro DELHI 🔝 >༒9540349809 🔝 genuine Escort Se...
call girls in Dwarka Sector 21 Metro DELHI 🔝 >༒9540349809 🔝 genuine Escort Se...call girls in Dwarka Sector 21 Metro DELHI 🔝 >༒9540349809 🔝 genuine Escort Se...
call girls in Dwarka Sector 21 Metro DELHI 🔝 >༒9540349809 🔝 genuine Escort Se...
 
Case Report Peripartum Cardiomyopathy.pptx
Case Report Peripartum Cardiomyopathy.pptxCase Report Peripartum Cardiomyopathy.pptx
Case Report Peripartum Cardiomyopathy.pptx
 
POST NATAL EXERCISES AND ITS IMPACT.pptx
POST NATAL EXERCISES AND ITS IMPACT.pptxPOST NATAL EXERCISES AND ITS IMPACT.pptx
POST NATAL EXERCISES AND ITS IMPACT.pptx
 
Glomerular Filtration rate and its determinants.pptx
Glomerular Filtration rate and its determinants.pptxGlomerular Filtration rate and its determinants.pptx
Glomerular Filtration rate and its determinants.pptx
 
97111 47426 Call Girls In Delhi MUNIRKAA
97111 47426 Call Girls In Delhi MUNIRKAA97111 47426 Call Girls In Delhi MUNIRKAA
97111 47426 Call Girls In Delhi MUNIRKAA
 
call girls in green park DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in green park  DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️call girls in green park  DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in green park DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
 
world health day presentation ppt download
world health day presentation ppt downloadworld health day presentation ppt download
world health day presentation ppt download
 
call girls in paharganj DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in paharganj DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️call girls in paharganj DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in paharganj DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
 
call girls in aerocity DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in aerocity DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️call girls in aerocity DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
call girls in aerocity DELHI 🔝 >༒9540349809 🔝 genuine Escort Service 🔝✔️✔️
 
Presentation on Parasympathetic Nervous System
Presentation on Parasympathetic Nervous SystemPresentation on Parasympathetic Nervous System
Presentation on Parasympathetic Nervous System
 
Presentació "Real-Life VR Integration for Mild Cognitive Impairment Rehabilit...
Presentació "Real-Life VR Integration for Mild Cognitive Impairment Rehabilit...Presentació "Real-Life VR Integration for Mild Cognitive Impairment Rehabilit...
Presentació "Real-Life VR Integration for Mild Cognitive Impairment Rehabilit...
 
PULMONARY EMBOLISM AND ITS MANAGEMENTS.pdf
PULMONARY EMBOLISM AND ITS MANAGEMENTS.pdfPULMONARY EMBOLISM AND ITS MANAGEMENTS.pdf
PULMONARY EMBOLISM AND ITS MANAGEMENTS.pdf
 
Presentation on General Anesthetics pdf.
Presentation on General Anesthetics pdf.Presentation on General Anesthetics pdf.
Presentation on General Anesthetics pdf.
 
Apiculture Chapter 1. Introduction 2.ppt
Apiculture Chapter 1. Introduction 2.pptApiculture Chapter 1. Introduction 2.ppt
Apiculture Chapter 1. Introduction 2.ppt
 
Music Therapy's Impact in Palliative Care| IAPCON2024| Dr. Tara Rajendran
Music Therapy's Impact in Palliative Care| IAPCON2024| Dr. Tara RajendranMusic Therapy's Impact in Palliative Care| IAPCON2024| Dr. Tara Rajendran
Music Therapy's Impact in Palliative Care| IAPCON2024| Dr. Tara Rajendran
 
Big Data Analysis Suggests COVID Vaccination Increases Excess Mortality Of ...
Big Data Analysis Suggests COVID  Vaccination Increases Excess Mortality Of  ...Big Data Analysis Suggests COVID  Vaccination Increases Excess Mortality Of  ...
Big Data Analysis Suggests COVID Vaccination Increases Excess Mortality Of ...
 
epilepsy and status epilepticus for undergraduate.pptx
epilepsy and status epilepticus  for undergraduate.pptxepilepsy and status epilepticus  for undergraduate.pptx
epilepsy and status epilepticus for undergraduate.pptx
 
Measurement of Radiation and Dosimetric Procedure.pptx
Measurement of Radiation and Dosimetric Procedure.pptxMeasurement of Radiation and Dosimetric Procedure.pptx
Measurement of Radiation and Dosimetric Procedure.pptx
 
VarSeq 2.6.0: Advancing Pharmacogenomics and Genomic Analysis
VarSeq 2.6.0: Advancing Pharmacogenomics and Genomic AnalysisVarSeq 2.6.0: Advancing Pharmacogenomics and Genomic Analysis
VarSeq 2.6.0: Advancing Pharmacogenomics and Genomic Analysis
 

14 strings

  • 2. Strings The string in C programming language is actually a one- dimensional array of characters which is terminated by a null character '0'.  Since stringstring is an array, the declaration of a string is the same as declaring a char array. char string1[30]; char str2[20] = “Initial value”; The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello." 08/23/152
  • 3. Declaration and Initialization of Strings  The following declaration and initialization create a string consisting of the word "Hello".  To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word “Hello.”  char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};  Another way of Initialization is (shortcut for initializing string)  char greeting[] = "Hello";  Note: We did not place the null character at the end of a string constant. The C compiler automatically places the '0' at the end of the string when it initializes the array.  Each character in the array occupies one byte of memory and the last character is always ‘0’.  It looks like two characters, but it is actually only one character, with the indicating that what follows it is something special.  ‘0’ is called null character.  Note that ‘0’ and ‘0’ are not same. ASCII value of ‘0’ is 0, whereas ASCII value of ‘0’ is 48. 08/23/153
  • 4. Importance of ‘0’ (null character ) The terminating null (‘0’) is important, because it is the only way the functions that work with a string can know where the string ends. In fact, a string not terminated by a ‘0’ is not really a string, but merely a collection of characters. Memory Representation of String: char greeting[] = "Hello"; 08/23/154 Address 5000 5001 5002 5003 5004 5005
  • 5. Printing String /* Program to demonstrate printing of a string */ main( ) { char name[ ] = "Klinsman" ; int i = 0 ; while ( i <= 7 ) { printf ( "%c", name[i] ) ; i++ ; } } And here is the output... Klinsman 08/23/155
  • 6. Printing String • Can we write the while loop without using the final value 7? • Yes:We can; because we know that each character array always ends with a ‘0’. Following program illustrates this. main( ) { char name[ ] = "Klinsman" ; int i = 0 ; while ( name[i] != ‘0’ ) { printf ( "%c", name[i] ) ; i++ ; } } And here is the output... Klinsman Note: This program doesn’t depend on the length of the string. 08/23/156
  • 7. Using %s format specifier  printf( ) function has got a sweet and simple way of printing string, as shown below. Note that printf( ) doesn’t print the ‘0’. main( ) { char name[ ] = "Klinsman" ; printf ( "%s", name ) ; }  The %s used in printf( ) is a format specification for printing out a string.  %s can be used to receive a string from the keyboard, as shown below. main( ) { char name[25] ; printf ( "Enter your name: " ) ; scanf ( "%s", name ) ; printf ( "Hello %s!", name ) ; } Note: Once you hit the enter key, scanf( ) places a ‘0’ in the array. 08/23/157 Sample output: Enter your name: Pratik Hello Pratik!
  • 8. Some Notable points  While entering the string using scanf( ) we must be cautious about two things: (a) The length of the string should not exceed the dimension of the character array. This is because the C compiler doesn’t perform bounds checking on character arrays. Hence, if you carelessly exceed the bounds there is always a danger of overwriting something important. (b) scanf( ) is not capable of receiving multi-word strings.Therefore names such as ‘Pratik Kumar’ would be unacceptable. The way to get around this limitation is by using the function gets( ). • The usage of functions gets( ) and its counterpart puts( ) is shown below. main( ) { char name[25] ; printf ( "Enter your full name: " ) ; gets ( name ) ; puts ( "Hello!" ) ; puts ( name ) ; } 08/23/158 And here is the output... Enter your full name: Pratik Kumar Hello! Pratik Kumar
  • 9. How to receive multi-word string using scanf() If we are prepared to take the trouble we can make scanf( ) accept multi-word strings by writing it in this manner: char name[25] ; printf ( "Enter your full name " ) ; scanf ( "%[^n]s", name ) ; 08/23/159
  • 10. Standard Library String Functions With every C compiler a large set of useful string handling library functions are provided. For Using following library function we need to include the headerfile string.h 08/23/1510 Function Use strlen Finds length of a string strlwr Converts a string to lowercase strupr Converts a string to uppercase strcat Appends one string at the end of another strcpy Copies a string into another strcmp Compares two strings strchr Finds first occurrence of a given character in a string strstr Finds first occurrence of a given string in another string
  • 11. Cont… Out of the above list we shall discuss the functions strlen( ), strcpy( ), strcat( ) and strcmp( ), since these are the most commonly used functions. strlen( ):This function counts the number of characters present in a string. main( ) { char arr[ ] = “Herry" ; int len1, len2 ; len1 = strlen ( arr ) ; len2 = strlen ( "Humpty Dumpty" ) ; printf ( "nstring = %s length = %d", arr, len1 ) ; printf ( "nstring = %s length = %d", "Humpty Dumpty", len2 ) ; }  Note: While calculating the length it doesn’t count ‘0’. 08/23/1511 O/P: string = Herry length = 5 string = Humpty Dumpty length = 13
  • 12. Writing own function xstrlen( ) which imitates strlen( ) int xstrlen ( char s[] ) { int length = 0,i=0 ; while ( s[i] != '0' ) { length++ ; i++ ; } return ( length ) ; } 08/23/1512 More efficient xstrlen int xstrlen ( char s[] ) { int i ; for(i=0; s[i] != '0' ;i++); return ( i ) ; }
  • 13. strcpy( ) This function copies the contents of one string into another. The base addresses of the source and target strings should be supplied to this function. Example of strcpy( ) void main() { char source[ ] = "Sayonara" ; char target[20] ; strcpy ( target, source ) ; printf ( "nsource string = %s", source ) ; printf ( "ntarget string = %s", target ) ; }  Note:It is our responsibility to see to it that the target string’s dimension is big enough to hold the string being copied into it. 08/23/1513 And here is the output... source string = Sayonara target string = Sayonara
  • 14. Implementing strcpy function void xstrcpy ( char t[], char s[] ) { int i; for ( i=0;s[i] != ‘0’ ; i++ ) { t[i] = s[i] ; } t [i]= '0' ; printf ( "nsource string = %s", s ) ; printf ( "ntarget string = %s", t ) ; } void main() { char source[ ] = "Sayonara" ; char target[20] ; xstrcpy ( target, source ) ; } 08/23/1514 And here is the output... source string = Sayonara target string = Sayonara
  • 15. strcat( )  This function concatenates the source string at the end of the target string.  For example, “Bombay” and “Nagpur” on concatenation would result into a string “BombayNagpur”.  Here is an example of strcat( ) main( ) { char source[ ] = "Folks!" ; char target[30] = "Hello" ; strcat ( target, source ) ; printf ( "nsource string = %s", source ) ; printf ( "ntarget string = %s", target ) ; } 08/23/1515 And here is the output... source string = Folks! target string = HelloFolks!
  • 16. strcmp( )  This is a function which compares two strings to find out whether they are same or different.  The two strings are compared character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first.  If the two strings are identical, strcmp( ) returns a value zero.  If they’re not identical, it returns the numeric difference between the ASCII values of the first non-matching pairs of characters.  Example main( ){ char string1[ ] = "Jerry" ; char string2[ ] = "Ferry" ; int i, j, k ; i = strcmp ( string1, "Jerry" ) ; j = strcmp ( string1, string2 ) ; k = strcmp ( string1, "Jerry boy" ) ; printf ( "n%d %d %d", i, j, k ) ; } 08/23/1516 And here is the output... 0 4 -32
  • 17. Cont… In the first call to strcmp( ), the two strings are identical—“Jerry” and “Jerry”—and the value returned by strcmp( ) is zero. In the second call, the first character of “Jerry” doesn't match with the first character of “Ferry” and the result is 4, which is the numeric difference between ASCII value of ‘J’ and ASCII value of ‘F’. In the third call to strcmp( ) “Jerry” doesn’t match with “Jerry boy”, because the null character at the end of “Jerry” doesn’t match the blank in “Jerry boy”. The value returned is -32, which is the value of null character minus the ASCII value of space, i.e., ‘0’ minus ‘ ’, which is equal to -32. Note: The exact value of mismatch will rarely concern us. Any non- zero value means there is a mismatch. 08/23/1517
  • 18. Homework Write the programms to implement the strcat and strcmp functions. void main(void) { char str1[25],str2[25]; int i,j; printf("nEnter First String:"); gets(str1); printf("nEnter Second String:"); gets(str2); for(i=0;str1[i]!=‘0’; i++) ; for(j=0; str2[j]!=‘0’; j++, i++) str1[i]=str2[j]; str1[i]='0'; printf("nConcatenated String is %s",str1); } 08/23/1518
  • 19. Program to compare two string #include<stdio.h> int compare(char a[], char b[]){ int c = 0; while( a[c] == b[c] ){ if( a[c] == '0' || b[c] == '0' ) break; c++; } if( a[c] == '0' && b[c] == '0' ) return 0; else return (a[c] - b[c]); } 08/23/1519 void main(void) { char str1[25],str2[25]; printf("nEnter First String:"); gets(str1); printf("nEnter Second String:"); gets(str2); int l= compare(str1,str2); if(l==0) printf("nsame=%d",l); else printf("nnot same=%d",l); }
  • 20. Characters #define FOUND 1 #define NOTFOUND 0 main( ) { char masterlist[6][40], yourname[40] ; int i, a, flag= NOTFOUND ; printf ( "nEnter MASTERLIST" ) ; for ( i = 0 ; i <= 5 ; i++ ) gets( &masterlist[i][0] ) ; printf ( "nEnter your name " ) ; gets(yourname ) ; for ( i = 0 ; i <= 5 ; i++ ){ a = strcmp ( &masterlist[i][0], yourname ) ; if ( a == 0 ){ printf ( "Welcome, you can enter into LT2" ) ; flag = FOUND ; break ; } } if ( flag == NOTFOUND ) printf ( "Sorry, you can not enter!" ) ; } 08/23/1520
  • 21. Notable Points  The order of the subscripts in the array declaration is important. The first subscript gives the number of names in the array, while the second subscript gives the length of each item in the array.  While comparing the strings through strcmp( ), note that the addresses of the strings are being passed to strcmp( ). As seen in the last lecture, if the two strings match, strcmp( ) would return a value 0, otherwise it would return a non-zero value.  char masterlist[6][10] will be stored in memory as shown in Fig.  Note that each string ends with a ‘0’.  Here, 65454, 65464, 65474, etc. are the base addresses of successive names. 08/23/1521