Operations on Strings
ESC101: Fundamentals of Computing
Some common operations on strings
2
ESC101: Fundamentals of Computing
Computing the length of a string
3
char str[10] = “Hello”;
int i = 0;
while(str[i] != ’\0’)
i++;
printf(“Length of %s is %d”,str,i);
ESC101: Fundamentals of Computing
Read a string and also compute its length
4
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;
}
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
5
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
6
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
7
ESC101: Fundamentals of Computing
string.h
8
char str1[] = "Hello", str2[] = "Helpo";
int i = strcmp(str1,str2);
printf("%d", i);
ESC101: Fundamentals of Computing
string.h
9
char str1[] = "Hello", str2[] = "Helpo";
printf("%d",strncmp(str1,str2,3));
0
ESC101: Fundamentals of Computing
string.h
10
case insensitive comparison.
-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
11
ESC101: Fundamentals of Computing
Another useful string function
12
ESC101: Fundamentals of Computing
Strings: Summary
13
14