Lecture VII
Lecture VII
String in C
What are Strings
For example,
Note:
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.
Example 1
main( )
{
char name[ ] = “Muhammed" ;
int i = 0 ;
while ( i <= 7)
{
printf ( "%c", name[i] ) ;
i++ ;
}
Example
main( )
{
char name[ ] = “Muhammed" ;
int i = 0 ;
while ( name[i] != `\0' )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
The %s format
main( )
{
char name[25] ;
printf ( "Enter your name " ) ;
scanf ( "%s", name ) ;
printf ( "Hello %s", name ) ;
}
Note
Inputting strings
Use of scanf
scanf("%s", word);
Copies input into word[]
9-13
Functions strcat and strlen
Functions strcat concatenate the fist string argument with the
second string argument.
strcat(dest, source);
9-14
Functions strcat and strlen
Function strlen is often used to check the length of a string (i.e., the
number of characters before the fist null character).
9-15
Distinction Between Characters and Strings
The representation of a char (e.g., ‘Q’) and a string (e.g., “Q”) is
essentially different.
A string is an array of characters ended with the
null character.
Q Q \0
9-16
String Comparison (1/2)
Suppose there are two strings, str1 and str2.
Thecondition str1 < str2 compare the initial
memory address of str1 and of str2.
The comparison between two strings is done by
comparing each corresponding character in them.
The characters are comapared against the ASCII table.
“thrill” < “throw” since ‘i’ < ‘o’;
“joy” < joyous“;
The standard string comparison uses the strcmp
and strncmp functions.
9-17
String Comparison (2/2)
Relationship Returned Value Example
str1 < str2 Negative “Hello”< “Hi”
str1 = str2 0 “Hi” = “Hi”
str1 > str2 Positive “Hi” > “Hello”
9-18
strcmp( )
Next class