90 Intermediate C Programming
printf (" %d n" , v) ;10
printf (" %c n" , v) ;11
return EXIT _SUCCES S ;12
}13
The output of this program is:
55
7
Why do the two lines print different values, even though both use v? The first printf
treats v as an integer by using %d. Hence, the printed value is 55. The second printf treats
v as a character by using %c. Since 55 is the ASCII value of character ’7’, 7 is printed on
screen. Note that in this case, using %c in printf causes the number 55 to be interpreted
as a character. C has different types, including char for characters and int for integers. A
char is an integer of a smaller range and can store one ASCII character. The character ’7’
has the value of 55. Even though they are both integers, the interpretations (%c or %d) are
different.
6.2.3 Finding Substrings: strstr
If string str1 is part of another string str2, we say str1 is a substring of str2. For
example, “str” is a substring of “structure” and “ure” is also a substring of “structure”.
“W” is a substring of “Welcome” but “sea” is not a substring of “sightseeing”.
If we want to determine whether one string is part of another string, we can use the
strstr function. This function takes two arguments: haystack and needle. The func-
tion attempts to locate needle within haystack. If needle is a substring of haystack,
strstr(haystack, needle) returns the address where the needle starts within haystack.
This address must not be NULL. If needle is not a substring of haystack, strstr(haystack,
needle) returns NULL. Please notice the order of the two arguments: The first is the longer
one. Here are two examples:
char haystack [] = { ’H ’ , ’e ’, ’l ’ , ’l’ , ’o ’, ’0 ’};1
char * chptr ; // a p o i nte r2
chptr = strstr ( haystack , "llo ");3
// chptr ’s value is the address of haystac k [2]4
chptr = strstr ( haystack , "XY" );5
// chptr ’s value is NULL6
In the first call of strstr, “llo” is part of “Hello” and the “llo” starts at the third element
(index is 2). Thus, strstr returns & haystack[2]. In the second call of strstr, “XY” is
not part of “Hello” and chptr’s value is NULL. The ending character ’0’ in haystack is not
considered when finding the needle.
6.2.4 Finding Characters: strchr
specific character. It returns the address of the first occurrence of the character within
the string. If this string does not contain the character, then strchr returns NULL. Here are
some examples:
char str [] = { ’H’ , ’e ’, ’l ’ , ’l ’, ’o ’, ’0 ’};1
char * chptr ; // a p o i nte r2
chptr = strchr ( str , ’H ’); // chptr ’s value is str [0] ’ s address3