Strings
Strings
1
Overview
Fundamentals of Strings and Characters
Character Handling Library
String Conversion Function
Standard Input/Output Library Functions
String Manipulation Functions
Comparison Functions
Search Functions
Memory Functions
2
A. Fundamentals of Strings and Characters
Characters
◦ Building blocks of programs
Every program is a sequence of meaningfully grouped characters
◦ Character constant
An int value represented as a character in single quotes
'z' represents the integer value of z
Strings
◦ Series of characters treated as a single unit
Can include letters, digits and special characters (*, /, $)
◦ String literal (string constant) - written in double quotes
"Hello"
◦ Strings are arrays of characters
String a pointer to first character
Value of string is the address of first character
3
Fundamentals of Strings and Characters
String definitions
◦ Define as a character array or a variable of type char *
char color[] = "blue";
char *colorPtr = "blue";
◦ Remember that strings represented as character arrays end
with '\0'
color has 5 elements
Inputting strings
◦ Use scanf
scanf("%s", word);
Copies input into word[]
Do not need & (because a string is a pointer)
◦ Remember to leave room in the array for '\0'
4
B. Character Handling Library
5
Prototype Function description
int isdigit( int c ); Returns a true value if c is a digit and 0 (false) otherwise.
int isalpha( int c ); Returns a true value if c is a letter and 0 otherwise.
int isalnum( int c ); Returns a true value if c is a digit or a letter and 0 otherwise.
int isxdigit( int c ); Returns a true value if c is a hexadecimal digit character and 0
otherwise. (See Appendix E, Number Systems, for
a detailed explanation of binary numbers, octal numbers, decimal
numbers and hexadecimal numbers.)
int islower( int c ); Returns a true value if c is a lowercase letter and 0 otherwise.
int isupper( int c ); Returns a true value if c is an uppercase letter and 0 otherwise.
6
Prototype Function description
int toupper( int c ); If c is a lowercase letter, toupper returns c as an uppercase
letter. Otherwise, toupper returns the argument unchanged.
int isspace( int c ); Returns a true value if c is a white-space character—newline
('\n'), space (' '), form feed ('\f'), carriage return ('\r'),
horizontal tab ('\t') or vertical tab ('\v')—and 0 otherwise.
int iscntrl( int c ); Returns a true value if c is a control character and 0 otherwise.
int ispunct( int c ); Returns a true value if c is a printing character other
than a space, a digit, or a letter and returns 0 otherwise.
int isprint( int c ); Returns a true value if c is a printing character including
a space (' ') and returns 0 otherwise.
int isgraph( int c ); Returns a true value if c is a printing character other
than a space (' ') and returns 0 otherwise.
7
isdigit() & isalpha()
1. #include <stdio.h>
2. #include <stdlib.h>
3. #include <ctype.h>
4. int main()
5. {
6.
7. printf("according to isdigit()\n %s digit \n\n", isdigit( '8' ) ? "8 is a " : "8 is not a ");
8.
9. printf("according to isalpha()\n %s letter \n\n", isalpha( 'A' ) ? "A is a " : "A is not a ");
10.
11. system("PAUSE");
12.
13. return 0;
14.
15. }
8
isalnum() & isxdigit()
1. #include <stdio.h>
2. #include <stdlib.h>
3. #include <ctype.h>
4. int main()
5. {
6. printf("according to isalnum()");
7. printf("\n----------------------");
8. printf("\n %s letter ", isalnum( 'A' ) ? "A is a" : "A is not a");
9. printf("\n %s letter ", isalnum( '8' ) ? "8 is a" : "8 is not a");
10. printf("\n %s letter ", isalnum( '#' ) ? "# is a" : "# is not a");
11.
12. printf("\n\naccording to isxdigit()");
13. printf("\n-----------------------");
14. printf("\n %s hexadecimal digit ", isxdigit( 'F' ) ? "F is a" : "F is nota ");
15. printf("\n %s hexadecimal digit ", isxdigit( 'J' ) ? "J is a" : "J is nota ");
16. printf("\n %s hexadecimal digit ", isxdigit( '7' ) ? "7 is a" : "7 is nota ");
17. printf("\n %s hexadecimal digit ", isxdigit( '$' ) ? "$ is a" : "$ is nota ");
18.
19. printf("\n");
20. system("PAUSE");
21.
22. return 0;
23. }
9
islower() & isupper()
1. #include <stdio.h>
2. #include <stdlib.h>
3. #include <ctype.h>
4. int main()
5. {
6. printf("according to islower()");
7. printf("\n----------------------");
8. printf("\n %s lowercase letter ", islower( 'A' ) ? "A is a" : "A is not a");
9. printf("\n %s lowercase letter ", islower( 'a' ) ? "a is a" : "a is not a");
10. printf("\n %s lowercase letter ", islower( '8' ) ? "8 is a" : "8 is not a");
11. printf("\n %s lowercase letter ", islower( '!' ) ? "! is a" : "! is not a");
12. printf("\n\naccording to isupper()");
13. printf("\n-----------------------");
14. printf("\n %s uppercase letter ", isupper( 'F' ) ? "F is a" : "F is not a");
15. printf("\n %s uppercase letter ", isupper( 'j' ) ? "j is a" : "j is not a");
16. printf("\n %s uppercase letter ", isupper( '7' ) ? "7 is a" : "7 is not a");
17. printf("\n %s uppercase letter ", isupper( '$' ) ? "$ is a" : "$ is not a");
18. printf("\n");
19. system("PAUSE");
20. return 0;
10
21. }
tolower() & toupper()
1. #include <stdio.h>
2. #include <stdlib.h>
3. #include <ctype.h>
4. int main()
5. {
6. printf("\nConverting uppercase to lowercase");
7. printf("\n-----------------------------------");
8. printf("\n A converted to lowercase letter is %c", tolower( 'A' ));
9. printf("\n\nConverting lowercase to uppercase");
10. printf("\n---------------------------------");
11. printf("\n a converted to uppercase letter is %c", toupper( 'a' ));
12.
13. printf("\n");
14. system("PAUSE");
15. return 0;
16. }
11
isspace() & iscntrl()
1. #include <stdio.h>
2. #include <stdlib.h>
3. #include <ctype.h>
4. int main()
5. {
6. printf("\nAccording to isspace()");
7. printf("\n----------------------");
8. printf("\n %s whitespace character ", isspace( ' ' ) ? "\' \' is a" : "\' \' is not a");
9. printf("\n %s whitespace character ", isspace( '\n' ) ? "Newline (\n) is a" : "Newline (\n) is not a");
10. printf("\n %s whitespace character ", isspace( '\t' ) ? "Horizontal tab is a" : "Horizontal tab is not a");
11. printf("\n %s whitespace character ", isspace( '!' ) ? "! is a" : "! is not a");
12. printf("\n\nAccording to iscntrl()");
13. printf("\n-----------------------");
14. printf("\n %s control character ", iscntrl( ' ' ) ? "\' \' is a" : "\' \' is not a");
15. printf("\n %s control character ", iscntrl( '\n' ) ? "Newline (\n) is a" : "Newline (\n) is not a");
16. printf("\n %s control character ", iscntrl( '\t' ) ? "Horizontal tab is a" : "Horizontal tab is not a");
17. printf("\n %s control character ", iscntrl( '$' ) ? "$ is a" : "$ is not a");
18. printf("\n");
19. system("PAUSE");
20. return 0;
12
21. }
ispunct() & isprint()
1. #include <stdio.h>
2. #include <stdlib.h>
3. #include <ctype.h>
4.
5. int main()
6. {
7. printf("\nAccording to ispunct()");
8. printf("\n----------------------");
9. printf("\n %s punctuation character ", ispunct( ';' ) ? "; is a" : "; is not a");
10. printf("\n %s punctuation character ", ispunct( 'Y' ) ? "Y is a" : "Y is not a");
11. printf("\n %s punctuation character ", ispunct( '#' ) ? "# is a" : "# is not a");
12.
13. printf("\n\nAccording to isprint()");
14. printf("\n-----------------------");
15. printf("\n %s printing character ", isprint( '$' ) ? "$ is a" : "$ is not a");
16. printf("\n %s printing character ", isprint( '\a' ) ? "Alert (\a) is a" : "Alert (\a) is not a");
17.
18. printf("\n");
19. system("PAUSE");
20.
21. return 0;
22. }
13
isgraph()
1. #include <stdio.h>
2. #include <stdlib.h>
3. #include <ctype.h>
4.
5. int main()
6.{
7. printf("\nAccording to isgraph()");
8. printf("\n----------------------");
9. printf("\n %s printing character other than a space", isgraph( ' ' ) ? "\' \' is a" : "\' \' is not a");
10. printf("\n %s printing character other than a space”, isgraph( 'Y' ) ? "Y is a" : "Y is not a");
11.
12. printf("\n");
13. system("PAUSE");
14.
15. return 0;
16. }
14
C. Standard Input/Output Library Functions
Functions in <stdio.h>
Used to manipulate character and string
data
15
Function prototype Function description
int getchar( void ); Inputs the next character from the standard input and
returns it as an integer.
char *gets( char *s ); Inputs characters from the standard input into the array
s until a newline or end-of-file character is encountered.
A terminating null character is appended to the array.
Returns the string inputted into s. Note that an error will
occur if s is not large enough to hold the string.
int putchar( int c ); Prints the character stored in c and returns it as an integer.
int puts( const char *s ); Prints the string s followed by a newline character. Returns
a non-zero integer if successful, or EOF if an error occurs.
16
getchar() & putchar()
17
gets() & puts()
18
sprintf() & sscanf()
char *box;
sprintf(box,”This is a sprintf”);
puts(box);
19
D. String Manipulation Functions of the
String Handling Library
String handling library has functions to
◦ Manipulate string data
◦ Search strings
◦ Tokenize strings
◦ Determine string length
20
Function prototype Function description
char *strcpy( char *s1, const char *s2 )
Copies string s2 into array s1. The value of s1 is returned.
char *strncpy( char *s1, const char *s2, size_t n )
Copies at most n characters of string s2 into array s1. The value of
s1 is returned.
char *strcat( char *s1, const char *s2 )
Appends string s2 to array s1. The first character of s2 overwrites
the terminating null character of s1. The value of s1 is returned.
21
strcpy() & strncpy()
strcpy
◦ Copies its second argument ( a string ) into
its first argument ( a char array that must be
large enough to store the string and its
terminating null char )
strncpy
◦ Equivalent to strcpy, except that strncpy
specifies the number of char to be copied
from the string into the array
22
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char x[] = "Happy Birthday to You";
char y[25];
char z[15];
strncpy(z,x,14);
z[14] = '\0';
printf("\nThe string in array z is: %s", z);
printf("\n");
system("PAUSE");
return 0;
}
23
strcat() & strncat()
strcat
◦ Appends its second argument ( a string) to its
first argument ( a char array containing a
string).
strncat
◦ Appends a specified number of characters
from the second string to the first string.
24
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s1[] = "Happy ";
char s2[] = "New Year ";
char s3[40] = "";
printf("\n");
system("PAUSE");
return 0;
}
25
E. Comparison Functions of the String-
Handling Library
Comparing strings
◦ Computer compares numeric ASCII codes of
characters in string
◦ Appendix D has a list of character codes
26
Function prototype Function description
int strcmp( const char *s1, const char *s2 );
Compares the string s1 with the string s2. The function returns
0, less than 0 or greater than 0 if s1 is equal to, less than or
greater than s2, respectively.
int strncmp( const char *s1, const char *s2, size_t n );
Compares up to n characters of the string s1 with the string s2.
The function returns 0, less than 0 or greater than 0 if s1 is
equal to, less than or greater than s2, respectively.
27
strcmp
◦ Compares its first string argument with its
second string argument, character by char
◦ Return 0 if string are equal
◦ Return –ve value if the first string is < second
string and +ve value if the first string >
second string
strncmp
◦ Equivalent to strcmp, except compares up to
a specified numbers of char.
28
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
const char *s1 = "Happy New Year";
const char *s2 = "Happy New Year";
const char *s3 = "Happy Holidays";
printf("\ns1 = %s",s1);
printf("\ns2 = %s",s2);
printf("\ns3 = %s",s3);
printf("\n\nAccording to strcmp()");
printf("\n\n-------------------");
printf("\nstrcmp(s1,s2) = %2d", strcmp(s1,s2));
printf("\nstrcmp(s1,s3) = %2d", strcmp(s1,s3));
printf("\nstrcmp(s3,s1) = %2d", strcmp(s3,s1));
printf("\n\nAccording to strncmp()");
printf("\n\n-------------------");
printf("\nstrncmp(s1,s3,6) = %d", strncmp(s1,s3,3));
printf("\nstrncmp(s1,s3,7) = %d", strncmp(s1,s3,9));
printf("\nstrncmp(s3,s1,7) = %d", strncmp(s3,s1,9));
printf("\n");
system("PAUSE");
return 0;
29
}
Function prototype Function description
30
Function prototype Function description
31
strchr
◦ Searches for the first occurrence of a
character in a string. If the char is found,
strchr returns a pointer to the char in the
string, otherwise, return NULL
32
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
const char *string = "This is a test";
char character1 = 'a';
char character2 = 'z';
printf("\n");
system("PAUSE");
return 0;
}
33
strcspn
◦ Determines the length of the initial part of
the string in its first argument that does not
contain any character from the string in its
second arguments
34
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
const char *string1 = "The value is 3.14159";
const char *string2 = "1234567890";
printf("\nThe length of the initial segment of string1 \n containing no characters from string2 = %u",
strcspn(string1, string2));
printf("\n");
system("PAUSE");
return 0;
}
35
strpbrk
◦ Searches its first string argument for the first
occurrence of any char in its second string
argument
◦ If a char from the second argument is found,
strpbrk returns a pointer to the char in the
first argument, otherwise return NULL
36
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
const char *string1 = "This is a test";
const char *string2 = "beware";
printf("\n");
system("PAUSE");
return 0;
}
37
strrchr
◦ Searches for the last occurrence of the
specified char in string.
◦ If the char is found, strrchr returns a pointer
to the char in the string, otherwise, return
NULL
38
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
const char *string1 = "A zoo has many animals including zebras";
int c = 'z';
printf("\n");
system("PAUSE");
return 0;
}
39
strspn
◦ Determines the length of the initial part of
the string in its first argument that contains
only char from the string in its second
argument.
◦ The function returns the length of the
segment.
40
1 /* Fig. 8.27: fig08_27.c
2 Using strspn */
3 #include <stdio.h>
4 #include <string.h>
5
6 int main( void )
7 {
8 /* initialize two char pointers */
9 const char *string1 = "The value is 3.14159";
10 const char *string2 = "aehi lsTuv";
11
12 printf( "%s%s\n%s%s\n\n%s\n%s%u\n",
13 "string1 = ", string1, "string2 = ", string2,
14 "The length of the initial segment of string1",
15 "containing only characters from string2 = ",
16 strspn( string1, string2 ) );
17
18 return 0; /* indicates successful termination */
19
20 } /* end main */ strspn returns the length of the
string1 = The value is 3.14159 initial segment of string1 that
string2 = aehi lsTuv
contains only characters from
The length of the initial segment of string1 string2
containing only characters from string2 = 13
41
strstr
◦ Searches for the first occurrence of its second
string argument in its first string argument.
◦ If the second string is found in the first string,
a pointer to the location of the string in the
first argument is returned.
42
strtok
◦ To break a string into a series of tokens
43
1 /* Fig. 8.29: fig08_29.c
2 Using strtok */
3 #include <stdio.h>
4 #include <string.h>
5
6 int main( void )
7 {
8 /* initialize array string */
9 char string[] = "This is a sentence with 7 tokens";
10 char *tokenPtr; /* create char pointer */
11
12 printf( "%s\n%s\n\n%s\n",
strtok “tokenizes” string by
13 "The string to be tokenized is:", string,
14 "The tokens are:" ); breaking it into tokens at each
15 space
16 tokenPtr = strtok( string, " " ); /* begin tokenizing sentence */
17
18 /* continue tokenizing sentence until tokenPtr becomes NULL */
19 while ( tokenPtr != NULL ) {
20 printf( "%s\n", tokenPtr );
21 tokenPtr = strtok( NULL, " " ); /* get next token */
22 } /* end while */
Calling strtok again and
passing it NULL continues
the tokenizing of the
previous string
44
Function prototype Function description
void *memcpy( void *s1, const void *s2, size_t n );
Copies n characters from the object pointed to by s2 into the
object pointed to by s1. A pointer to the resulting object is
returned.
void *memmove( void *s1, const void *s2, size_t n );
Copies n characters from the object pointed to by s2 into the
object pointed to by s1. The copy is performed as if
the characters were first copied from the object pointed to by s2
into a temporary array and then from the temporary array into
the object pointed to by s1. A pointer to the resulting object is
returned.
int memcmp( const void *s1, const void *s2, size_t n );
Compares the first n characters of the objects pointed to
by s1 and s2. The function returns 0, less than 0 or
greater than 0 if s1 is equal to, less than or greater than s2.
void *memchr( const void *s, int c, size_t n );
Locates the first occurrence of c (converted to unsigned
char) in the first n characters of the object pointed to by s. If
c is found, a pointer to c in the object is returned. Otherwise,
NULL is returned.
void *memset( void *s, int c, size_t n );
Copies c (converted to unsigned char) into the first n
characters of the object pointed to by s. A pointer to the result is
returned.
45
memcpy copies the first 17
1 /* Fig. 8.31: fig08_31.c
characters from object s2 into
2 Using memcpy */
3 #include <stdio.h> object s1
4 #include <string.h>
5
6 int main( void )
7 {
8 char s1[ 17 ]; /* create char array s1 */
9 char s2[] = "Copy this string"; /* initialize char array s2 */
10
11 memcpy( s1, s2, 17 );
12 printf( "%s\n%s\"%s\"\n",
13 "After s2 is copied into s1 with memcpy,",
14 "s1 contains ", s1 );
15
16 return 0; /* indicates successful termination */
17
18 } /* end main */
46
1 /* Fig. 8.32: fig08_32.c
2 Using memmove */
3 #include <stdio.h>
4 #include <string.h>
5
6 int main( void )
7 {
8 char x[] = "Home Sweet Home"; /* initialize char array x */
9
10 printf( "%s%s\n", "The string in array x before memmove is: ", x );
11 printf( "%s%s\n", "The string in array x after memmove is: ",
12 memmove( x, &x[ 5 ], 10 ) );
13 memmove copies the
14 return 0; /* indicates successful termination */ first 10 characters
15
from x[5] into object
16 } /* end main */
x by means of a
The string in array x before memmove is: Home Sweet Home
The string in array x after memmove is: Sweet Home Home temporary array
47
1 /* Fig. 8.33: fig08_33.c
2 Using memcmp */
3 #include <stdio.h>
4 #include <string.h>
5
6 int main( void )
7 {
8 char s1[] = "ABCDEFG"; /* initialize char array s1 */
9 char s2[] = "ABCDXYZ"; /* initialize char array s2 */
10
11 printf( "%s%s\n%s%s\n\n%s%2d\n%s%2d\n%s%2d\n",
12 "s1 = ", s1, "s2 = ", s2,
13 "memcmp( s1, s2, 4 ) = ", memcmp( s1, s2, 4 ),
14 "memcmp( s1, s2, 7 ) = ", memcmp( s1, s2, 7 ),
15 "memcmp( s2, s1, 7 ) = ", memcmp( s2, s1, 7 ) );
16
17 return 0; /* indicate successful termination */
18 memcmp compares
19 } /* end main */
the first 4
s1 = ABCDEFG
s2 = ABCDXYZ
characters of
objects s1 and s2
memcmp( s1, s2, 4 ) = 0
memcmp( s1, s2, 7 ) = -1
memcmp( s2, s1, 7 ) = 1
48
1 /* Fig. 8.34: fig08_34.c
2 Using memchr */
3 #include <stdio.h>
4 #include <string.h>
5
6 int main( void )
7 {
8 const char *s = "This is a string"; /* initialize char pointer */
9
10 printf( "%s\'%c\'%s\"%s\"\n",
11 "The remainder of s after character ", 'r',
12 " is found is ", memchr( s, 'r', 16 ) );
13
14 return 0; /* indicates successful termination */
memchr locates the
15 first occurrence of
16 } /* end main */ the character r
The remainder of s after character 'r' is found is "ring" inside the first 16
characters of
object s
49
1 /* Fig. 8.35: fig08_35.c
2 Using memset */
3 #include <stdio.h>
4 #include <string.h>
5
6 int main( void )
7 {
8 char string1[ 15 ] = "BBBBBBBBBBBBBB"; /* initialize string1 */
9
10 printf( "string1 = %s\n", string1 );
11 printf( "string1 after memset = %s\n", memset( string1, 'b', 7 ) );
12
13 return 0; /* indicates successful termination */
14
15 } /* end main */
string1 = BBBBBBBBBBBBBB
string1 after memset = bbbbbbbBBBBBBB
memset copies the
character b into the first
7 characters of object
string1
50
Function prototype Function description
char *strerror( int errornum );
Maps errornum into a full text string in a locale-specific
manner (e.g. the message may appear in different languages
based on its location). A pointer to the string is returned.
size_t strlen( const char *s );
Determines the length of string s. The number of characters
preceding the terminating null character is returned.
51
strerror()
#include <stdio.h>
#include <stdlib.h>
#include <string.h> strerror returns an error
message based on the number
int main()
passed to it
{
printf("\n Error 1 = \"%s\"", strerror(1));
printf("\n Error 2 = \"%s\"", strerror(2));
printf("\n Error 3 = \"%s\"", strerror(3));
printf("\n Error 4 = \"%s\"", strerror(4));
printf("\n Error 5 = \"%s\"", strerror(5));
printf("\n Error 6 = \"%s\"", strerror(6));
printf("\n");
system("PAUSE");
return 0;
}
52
1 /* Fig. 8.38: fig08_38.c
2 Using strlen */
3 #include <stdio.h>
4 #include <string.h>
5
6 int main( void )
7 {
8 /* initialize 3 char pointers */
9 const char *string1 = "abcdefghijklmnopqrstuvwxyz";
10 const char *string2 = "four";
11 const char *string3 = "Boston";
12
13 printf("%s\"%s\"%s%lu\n%s\"%s\"%s%lu\n%s\"%s\"%s%lu\n",
14 "The length of ", string1, " is ",
15 ( unsigned long ) strlen( string1 ), strlen returns the length of
16 "The length of ", string2, " is ", string1
17 ( unsigned long ) strlen( string2 ),
18 "The length of ", string3, " is ",
19 ( unsigned long ) strlen( string3 ) );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */
53
References
54
END
55