SlideShare a Scribd company logo
1 of 22
ESC101: Fundamentals of
Computing
 String: A sequence of characters enclosed in double quotes “ “
 A string can be declared and initialized as
 Internally, a string is stored as a char array whose last element is ‘0’
Strings
char str[50] = "Hello World";
char str[50] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’,’0’};
The null character
Equivalent to “Hello World”
ESC101: Fundamentals of
Computing
 Character array: Each element is a character
 String: A sequence of characters enclosed in double quotes “ “
 A string can be declared and initialized as
 Internally, a string is stored as a char array whose last element is ‘0’
Character Arrays and Strings
char str[50] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’};
char str[50] = "Hello World";
char str[50] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’,’0’};
The null character
Note that not all 50
elements were initialized
here (only first 11 were)
Equivalent to “Hello World”
ESC101: Fundamentals of
Computing
 Used to signal the end of a string (has ASCII code 0)
 Character arrays with a null character are treated as strings
 Mr. C will stop reading a character array after he sees 0
char str[50] = {‘H’,’e’,’l’,’0’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’};
printf("%s",str); Hmm … string is only till the 0. I will
consider anything after that as garbage
Hel
The null character 0
Note: We use %s
to print a string
ESC101: Fundamentals of
Computing
Different ways to declare/initialize a string
 Some valid ways to declare and initialize a string
char str[] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’, ’0’};
char str[] = "Hello World";
char str[50] = "Hello World"; You need not specify the size of
string. But if you specify the size,
it should be at least one more
than the length of the string
char str[50] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’, ’0’};
char str[12] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’, ’0’};
char str[12] = "Hello World";
Note that Hello World
has length 11, so size
12 is fine. Less than
that may cause issues
ESC101: Fundamentals of
Computing
Null character ‘0’ ends the string
‘I’ ‘m’ ‘G’ ‘R’ ‘8’ ‘D’ ‘O’ ‘N’ ‘0’
‘a’
‘ ’ ‘ 0’
str
str[0] str[2] str[4] str[6] str[8] str[11]
char str[]=“I am GR8DON”;
str[4]=‘0’;
printf(“%s”, str); I am
Output
int i;
for (i=0; i < 11; i++) {
putchar(str[i]);
}
Output
I amGR8DON
The character
‘0’ may be
printed
differently on
screen
depending on
terminal
settings.
5
Can still print all elements in the char array…
ESC101: Fundamentals of
Computing
When we say
Mr C will store a 0 after last character ‘e’
Warning: uninitialized character arrays contain junk
char str[6] = "Nice";
str N i c e 0
char str = "A";
putchar(str);
$
Strings are character
arrays. “A” is a string.
‘A’ is a character
Somewhat like saying
int num = {3,2,1};
Mr. C and the null character
ESC101: Fundamentals of
Computing
In fact when we read a string using gets or scanf, Mr C yet
again automatically puts a 0 at the end
str N i c e 0
So
char str[6] = "Nice";
scanf("%s",str);
S o 0
printf("%s",str);
We did not write
&str in scanf?
Will learn about
this in a few weeks
No, since str is
the whole array
The rest of the char
array is still there
Yes, I did not erase ‘e’ and
‘0’ that were already there. I
just overwrote the first two
characters and then put a 0
Mr. C and the null character
So
Will see it
shortly
ESC101: Fundamentals of
Computing
Operations on Strings
ESC101: Fundamentals of
Computing
Use %s to read string from input
No & needed since the whole char array is being read
Mr C will automatically append a 0 at the end
Drawback: stops reading the moment any whitespace character
is seen (n, t or space)
Very Risky: if user enters more characters than size of char array
– segmentation fault!
Caution: Prutor will give runtime error if user enters too many
more characters than space is available.
gcc and other industrial compilers will also give segfaults
scanf("%s",str);
scanf with Strings Will discuss the
reason in detail
when we study
Pointers
ESC101: Fundamentals of
Computing
#include <stdio.h>
int main() {
char str1[20], str2[20];
scanf("%s",str1);
scanf("%s",str2);
printf("%s + %sn", str1, str2);
return 0;
}
INPUT
IIT Kanpur
OUTPUT
IIT + Kanpur
INPUT
I am DON
OUTPUT
I + am
scanf with Strings: An Example Read “I” as first
string, stopped
when saw white
space and read
“am” as second
string, stopped
again when saw
the next space
(“DON” ignored)
Not scared of you
DON. I won’t
read you 
ESC101: Fundamentals of
Computing
Some common operations on strings
• Compute the length of a string.
• Copy one string into another string variable
• Concatenate one string with another.
• Search for a substring in a given string.
• Reverse a string
• Find first/last/k-th occurrence of a character in a
string
– … and more
• Case sensitive/insensitive versions
Can solve all these
problems using
loops, looking at the
string char by char
Or by using pre-
defined functions in
a header file called
string.h 
ESC101: Fundamentals of
Computing
Computing the length of a string
char str[10] = “Hello”;
int i = 0;
while(str[i] != ’0’)
i++;
printf(“Length of %s is %d”,str,i);
How to find the
length of not a
fixed string but
any string
provided by
user?
Count the length
char by char using
getchar in a loop, or
use strlen function
in string.h
ESC101: Fundamentals of
Computing
Read a string and also compute its length
int main() {
char str[100];
char ch;
int i = 0;
ch = getchar();
while(1){
if(ch==‘n’) break;
str[i] = ch;
++i;
ch = getchar();
}
str[i] = ‘0’;
printf("Length of %s is %d",str,i);
return 0;
}
I will enter a string
and end it with
newline. Please
store it in a string
named str and
compute its length
Read the first
character
If found a newline, break
Read the next character
Let’s put ‘0’ in the end to
mark the end of string
Not a newline. Store the read character at index i of str
Will store the
length
ESC101: Fundamentals of
Computing
Copying a string
• We cannot copy content of one string variable to
other using assignment operator
– This is true for any array variable.
– Error because array initializer must be a list (comma
separated values in {}) or a string.
• We need to do element-wise copying
char str1[] = "Hello";
char str2[] = str1;
WRONG
Array type is not
assignable.
C Pointers needed
(will see this later)!
ESC101: Fundamentals of
Computing
Copying a string element-by-element
• Goal: Copy contents of string src into string dest.
• Declare dest with size at least as large as src.
• Use a loop to copy elements one-by-one
• Note the use of ‘0’ for loop termination
char src[100] = “Hello World”;
char dest[100];
int i;
for (i = 0; src[i] != '0’; i++)
dest[i] = src[i];
dest[i] = '0';
Part of the loop
Not part of the loop
ESC101: Fundamentals of
Computing
string.h
• Many string operations are already implemented in string.h
• It is a header file (“h” for header) with various functions
on Strings
• strlen(s): returns length of string s (without ‘0’)
• strcpy(d, s): copies s into d
• strcat(d, s): appends s at the end of d (‘0’ is moved to the
end of result)
ESC101: Fundamentals of
Computing
string.h
• strcmp(s1, s2): return an integer less than, equal
to, or greater than zero if s1 is found, respectively,
to be less than, to match, or be greater than s2.
• Example:
• Prints the value ‘l’-’p’ which is -4.
char str1[] = "Hello", str2[] = "Helpo";
int i = strcmp(str1,str2);
printf("%d", i);
ESC101: Fundamentals of
Computing
string.h
• strncpy(d, s, n)
• strncat(d, s, n)
• strncmp(d, s, n)
– restrict the function to “n” characters at
most (argument n is an integer)
– first two functions-- Truncate the string s
to the first “n” characters.
– third function-- Truncate the strings d, s to
the first “n” characters.
char str1[] = "Hello", str2[] = "Helpo";
printf("%d",strncmp(str1,str2,3)); 0
ESC101: Fundamentals of
Computing
string.h
• strcasecmp, strncasecmp:
case insensitive comparison.
• Example:
• strcmp gives -32 because ‘E’ < ‘e’ .
– ‘E’-‘e’ = -32 .
• strcasecmp finds the first 3 characters the same
(ignoring case) gives -4 because ‘l’ - ‘p’ = -4
-32 -4
char str1[] = "HELLO", str2[] = "Helpo";
int i = strcmp(str1,str2);
int j = strcasecmp(str1,str2);
printf("%d %d", i, j);
ESC101: Fundamentals of
Computing
string.h
• Many more utility functions.
• strupr(s) : converts lower to upper case.
• strlwr(s) : converts upper to lower case.
• strstr(S,s) : searches string s in string S (example:
strstr(“Hello”,”ll”);). Returns a pointer(memory
address) to the first occurrence.
• All functions depend on ‘0’ as the end-of-string
marker.
ESC101: Fundamentals of
Computing
atoi(str): converts a string into integer, e.g. atoi(“123”) will return
123 (integer). So we can write int a = atoi(“123”);
atoi(str) will keep reading the string str until it finds a non-
digit character in str and will return the integer containing the
read digit characters in str
atoi(“12abc3”) will return 12
If no digit symbols found in str, atoi(str) will return 0
If the read integer is larger than the range of integers, garbage
will be returned
Other function atof(str), atol(str) – return float and long
Can also convert int/long to string (itoa, ltoa, etc)
Another useful string function
ESC101: Fundamentals of
Computing
A very special non-character – cannot be printed
Signals end of input (no more characters in input)
stdio.h gives you a named constant EOF for convenience
Has no ASCII value – but internally stored as -1
Recall characters have ASCII values from 0 to 127 only
getchar() will read EOF as a character but not scanf/gets
Be careful, do not
confuse EOF with
NULL and n.
NULL and n are valid
characters with proper
ASCII values
EOF (end of file)

More Related Content

Similar to INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx

C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11Rumman Ansari
 
SPL 13 | Character Array(String) in C
SPL 13 | Character Array(String) in CSPL 13 | Character Array(String) in C
SPL 13 | Character Array(String) in CMohammad Imam Hossain
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTSasideepa
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTSasideepa
 
Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01Md. Ashikur Rahman
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programmingmikeymanjiro2090
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
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
 
Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_KarthicaMarasamy
 
Character array (strings)
Character array (strings)Character array (strings)
Character array (strings)sangrampatil81
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsJamesChristianGadian
 
lecture-5 string.pptx
lecture-5 string.pptxlecture-5 string.pptx
lecture-5 string.pptxDilanAlmsa
 

Similar to INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx (20)

COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
 
SPL 13 | Character Array(String) in C
SPL 13 | Character Array(String) in CSPL 13 | Character Array(String) in C
SPL 13 | Character Array(String) in C
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPT
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
 
Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
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++
 
Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_
 
14 strings
14 strings14 strings
14 strings
 
[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
StringString
String
 
Character array (strings)
Character array (strings)Character array (strings)
Character array (strings)
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
 
lecture-5 string.pptx
lecture-5 string.pptxlecture-5 string.pptx
lecture-5 string.pptx
 
Lecture 2. mte 407
Lecture 2. mte 407Lecture 2. mte 407
Lecture 2. mte 407
 
Unit 2
Unit 2Unit 2
Unit 2
 
String notes
String notesString notes
String notes
 

More from AbhimanyuChaure

INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxAbhimanyuChaure
 
INDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptx
INDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptxINDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptx
INDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptxAbhimanyuChaure
 
b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...
b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...
b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...AbhimanyuChaure
 
915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...
915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...
915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...AbhimanyuChaure
 
28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...
28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...
28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...AbhimanyuChaure
 
2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...
2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...
2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...AbhimanyuChaure
 
IITK ESC 111M Lec02.pptx .
IITK ESC 111M Lec02.pptx               .IITK ESC 111M Lec02.pptx               .
IITK ESC 111M Lec02.pptx .AbhimanyuChaure
 

More from AbhimanyuChaure (7)

INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
 
INDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptx
INDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptxINDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptx
INDIAN INSTITUTE OF TECHNOLOGY OF KANPURESC 111M Lec03.pptx
 
b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...
b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...
b5f1d7dac0b7d87e4f41a5509c1bf602e0d18aae0f9177cb406348a0edf59507_hello iitk L...
 
915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...
915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...
915d511043d1509957e5b45ed827a5a9652f6759581a3682f5aabb6b0bccc5bd_Helloiitk Le...
 
28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...
28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...
28f7f76ecd0fa8c132d87392a65507f78661379cfef5faa7ab8f733625de2723_Helloiit Lec...
 
2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...
2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...
2480b48c99ef4e3b94038d2680df02fe96bc196b029703c1929ec2575bed8eb9_Helloiitk Le...
 
IITK ESC 111M Lec02.pptx .
IITK ESC 111M Lec02.pptx               .IITK ESC 111M Lec02.pptx               .
IITK ESC 111M Lec02.pptx .
 

Recently uploaded

Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 

Recently uploaded (20)

Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 

INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx

  • 1. ESC101: Fundamentals of Computing  String: A sequence of characters enclosed in double quotes “ “  A string can be declared and initialized as  Internally, a string is stored as a char array whose last element is ‘0’ Strings char str[50] = "Hello World"; char str[50] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’,’0’}; The null character Equivalent to “Hello World”
  • 2. ESC101: Fundamentals of Computing  Character array: Each element is a character  String: A sequence of characters enclosed in double quotes “ “  A string can be declared and initialized as  Internally, a string is stored as a char array whose last element is ‘0’ Character Arrays and Strings char str[50] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’}; char str[50] = "Hello World"; char str[50] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’,’0’}; The null character Note that not all 50 elements were initialized here (only first 11 were) Equivalent to “Hello World”
  • 3. ESC101: Fundamentals of Computing  Used to signal the end of a string (has ASCII code 0)  Character arrays with a null character are treated as strings  Mr. C will stop reading a character array after he sees 0 char str[50] = {‘H’,’e’,’l’,’0’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’}; printf("%s",str); Hmm … string is only till the 0. I will consider anything after that as garbage Hel The null character 0 Note: We use %s to print a string
  • 4. ESC101: Fundamentals of Computing Different ways to declare/initialize a string  Some valid ways to declare and initialize a string char str[] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’, ’0’}; char str[] = "Hello World"; char str[50] = "Hello World"; You need not specify the size of string. But if you specify the size, it should be at least one more than the length of the string char str[50] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’, ’0’}; char str[12] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,‘W’,’o’,’r’,’l’,’d’, ’0’}; char str[12] = "Hello World"; Note that Hello World has length 11, so size 12 is fine. Less than that may cause issues
  • 5. ESC101: Fundamentals of Computing Null character ‘0’ ends the string ‘I’ ‘m’ ‘G’ ‘R’ ‘8’ ‘D’ ‘O’ ‘N’ ‘0’ ‘a’ ‘ ’ ‘ 0’ str str[0] str[2] str[4] str[6] str[8] str[11] char str[]=“I am GR8DON”; str[4]=‘0’; printf(“%s”, str); I am Output int i; for (i=0; i < 11; i++) { putchar(str[i]); } Output I amGR8DON The character ‘0’ may be printed differently on screen depending on terminal settings. 5 Can still print all elements in the char array…
  • 6. ESC101: Fundamentals of Computing When we say Mr C will store a 0 after last character ‘e’ Warning: uninitialized character arrays contain junk char str[6] = "Nice"; str N i c e 0 char str = "A"; putchar(str); $ Strings are character arrays. “A” is a string. ‘A’ is a character Somewhat like saying int num = {3,2,1}; Mr. C and the null character
  • 7. ESC101: Fundamentals of Computing In fact when we read a string using gets or scanf, Mr C yet again automatically puts a 0 at the end str N i c e 0 So char str[6] = "Nice"; scanf("%s",str); S o 0 printf("%s",str); We did not write &str in scanf? Will learn about this in a few weeks No, since str is the whole array The rest of the char array is still there Yes, I did not erase ‘e’ and ‘0’ that were already there. I just overwrote the first two characters and then put a 0 Mr. C and the null character So Will see it shortly
  • 9. ESC101: Fundamentals of Computing Use %s to read string from input No & needed since the whole char array is being read Mr C will automatically append a 0 at the end Drawback: stops reading the moment any whitespace character is seen (n, t or space) Very Risky: if user enters more characters than size of char array – segmentation fault! Caution: Prutor will give runtime error if user enters too many more characters than space is available. gcc and other industrial compilers will also give segfaults scanf("%s",str); scanf with Strings Will discuss the reason in detail when we study Pointers
  • 10. ESC101: Fundamentals of Computing #include <stdio.h> int main() { char str1[20], str2[20]; scanf("%s",str1); scanf("%s",str2); printf("%s + %sn", str1, str2); return 0; } INPUT IIT Kanpur OUTPUT IIT + Kanpur INPUT I am DON OUTPUT I + am scanf with Strings: An Example Read “I” as first string, stopped when saw white space and read “am” as second string, stopped again when saw the next space (“DON” ignored) Not scared of you DON. I won’t read you 
  • 11. ESC101: Fundamentals of Computing Some common operations on strings • Compute the length of a string. • Copy one string into another string variable • Concatenate one string with another. • Search for a substring in a given string. • Reverse a string • Find first/last/k-th occurrence of a character in a string – … and more • Case sensitive/insensitive versions Can solve all these problems using loops, looking at the string char by char Or by using pre- defined functions in a header file called string.h 
  • 12. ESC101: Fundamentals of Computing Computing the length of a string char str[10] = “Hello”; int i = 0; while(str[i] != ’0’) i++; printf(“Length of %s is %d”,str,i); How to find the length of not a fixed string but any string provided by user? Count the length char by char using getchar in a loop, or use strlen function in string.h
  • 13. ESC101: Fundamentals of Computing Read a string and also compute its length int main() { char str[100]; char ch; int i = 0; ch = getchar(); while(1){ if(ch==‘n’) break; str[i] = ch; ++i; ch = getchar(); } str[i] = ‘0’; printf("Length of %s is %d",str,i); return 0; } I will enter a string and end it with newline. Please store it in a string named str and compute its length Read the first character If found a newline, break Read the next character Let’s put ‘0’ in the end to mark the end of string Not a newline. Store the read character at index i of str Will store the length
  • 14. ESC101: Fundamentals of Computing Copying a string • We cannot copy content of one string variable to other using assignment operator – This is true for any array variable. – Error because array initializer must be a list (comma separated values in {}) or a string. • We need to do element-wise copying char str1[] = "Hello"; char str2[] = str1; WRONG Array type is not assignable. C Pointers needed (will see this later)!
  • 15. ESC101: Fundamentals of Computing Copying a string element-by-element • Goal: Copy contents of string src into string dest. • Declare dest with size at least as large as src. • Use a loop to copy elements one-by-one • Note the use of ‘0’ for loop termination char src[100] = “Hello World”; char dest[100]; int i; for (i = 0; src[i] != '0’; i++) dest[i] = src[i]; dest[i] = '0'; Part of the loop Not part of the loop
  • 16. ESC101: Fundamentals of Computing string.h • Many string operations are already implemented in string.h • It is a header file (“h” for header) with various functions on Strings • strlen(s): returns length of string s (without ‘0’) • strcpy(d, s): copies s into d • strcat(d, s): appends s at the end of d (‘0’ is moved to the end of result)
  • 17. ESC101: Fundamentals of Computing string.h • strcmp(s1, s2): return an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2. • Example: • Prints the value ‘l’-’p’ which is -4. char str1[] = "Hello", str2[] = "Helpo"; int i = strcmp(str1,str2); printf("%d", i);
  • 18. ESC101: Fundamentals of Computing string.h • strncpy(d, s, n) • strncat(d, s, n) • strncmp(d, s, n) – restrict the function to “n” characters at most (argument n is an integer) – first two functions-- Truncate the string s to the first “n” characters. – third function-- Truncate the strings d, s to the first “n” characters. char str1[] = "Hello", str2[] = "Helpo"; printf("%d",strncmp(str1,str2,3)); 0
  • 19. ESC101: Fundamentals of Computing string.h • strcasecmp, strncasecmp: case insensitive comparison. • Example: • strcmp gives -32 because ‘E’ < ‘e’ . – ‘E’-‘e’ = -32 . • strcasecmp finds the first 3 characters the same (ignoring case) gives -4 because ‘l’ - ‘p’ = -4 -32 -4 char str1[] = "HELLO", str2[] = "Helpo"; int i = strcmp(str1,str2); int j = strcasecmp(str1,str2); printf("%d %d", i, j);
  • 20. ESC101: Fundamentals of Computing string.h • Many more utility functions. • strupr(s) : converts lower to upper case. • strlwr(s) : converts upper to lower case. • strstr(S,s) : searches string s in string S (example: strstr(“Hello”,”ll”);). Returns a pointer(memory address) to the first occurrence. • All functions depend on ‘0’ as the end-of-string marker.
  • 21. ESC101: Fundamentals of Computing atoi(str): converts a string into integer, e.g. atoi(“123”) will return 123 (integer). So we can write int a = atoi(“123”); atoi(str) will keep reading the string str until it finds a non- digit character in str and will return the integer containing the read digit characters in str atoi(“12abc3”) will return 12 If no digit symbols found in str, atoi(str) will return 0 If the read integer is larger than the range of integers, garbage will be returned Other function atof(str), atol(str) – return float and long Can also convert int/long to string (itoa, ltoa, etc) Another useful string function
  • 22. ESC101: Fundamentals of Computing A very special non-character – cannot be printed Signals end of input (no more characters in input) stdio.h gives you a named constant EOF for convenience Has no ASCII value – but internally stored as -1 Recall characters have ASCII values from 0 to 127 only getchar() will read EOF as a character but not scanf/gets Be careful, do not confuse EOF with NULL and n. NULL and n are valid characters with proper ASCII values EOF (end of file)