String PPTs
String PPTs
3
Character Arrays and Strings
char C[8] = { ‘k', ‘a', ‘u', ‘s', ‘h', ‘a', ‘l', '\0' };
• C[0] gets the value ‘k', C[1] the value ‘a', and so on. The last (7th)
location receives the null character ‘\0’
• Null-terminated (last character is ‘\0’) character arrays are also called
strings
• Strings can be initialized in an alternative way. The last declaration is
equivalent to:
char C[8] = “kaushal";
• The trailing null character is missing here. C automatically puts it at the
end if you define it like this
• Note also that for individual characters, C uses single quotes, whereas
for strings, it uses double quotes
4
Reading strings: %s format
void main()
{
char name[25];
scanf("%s", name);
printf("Name = %s \n", name);
}
5
An example
void main()
{
#define SIZE 25 Seen on screen
int i, count=0;
char name[SIZE]; Typed as input
scanf("%s", name); Satyanarayana
printf("Name = %s \n", name);
Name = Satyanarayana
for (i=0; name[i]!='\0'; i++)
if (name[i] == 'a') count++; Total a's = 6
printf("Total a's = %d\n", count);
}
Printed by program
Note that character strings read
in %s format end with ‘\0’
6
Library Functions for String Handling
• You can write your own C code to do different
operations on strings like finding the length of a
string, copying one string to another, appending one
string to the end of another etc.
• C library provides standard functions for these that
you can call, so no need to write your own code
• To use them, you must do
#include <string.h>
At the beginning of your program (after #include <stdio.h>)
7
String functions we will see
8
strlen()
• Takes a null-terminated
strings (we routinely refer to
the char pointer that points to
a null-terminated char array as
a string)
• Returns the length of the
string, not counting the
null (\0) character
9
strcat()
• Takes 2 strings as
arguments,
concatenates them, and
puts the result in s1.
Returns s1.
Programmer must
ensure that s1 points to
enough space to hold
the result.
10
strcmp()
Two strings are passed
as arguments. An
integer is returned
that is less than,
equal to, or greater
than 0, depending
on whether s1 is
lexicographically
less than, equal to,
or greater than s2.
11
strcpy()
12
Example: Using string functions
int main()
{
char s1[ ] = "beautiful big sky country", Output
s2[ ] = "how now brown cow";
25
printf("%d\n",strlen (s1));
printf("%d\n",strlen (s2+8)); 9
printf("%d\n", strcmp(s1,s2)); -1
printf("%s\n",s1+10); big sky country
strcpy(s1+10,s2+8); beautiful brown cows!
strcat(s1,"s!");
printf("%s\n", s1);
return 0;
}
13
Questions???