This is an presentation of c programming language which is taught at indian institute of technology kanpur in first year first semester under bachelor of technology or bachelor of science.
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)