C-Programming-Class 9
C-Programming-Class 9
Manipulating Strings
1
Session Objectives
2
Session Topics
• String Length and Storage
• Copying Strings
• Concatenating Strings
• Comparing Strings
• Searching Strings
• String Conversions
• Miscellaneous String Functions
• String-to-Number Conversions
• Character Test Functions
3
String Length and Storage
• A string is a sequence of characters, with its beginning
indicated by a pointer and its end marked by the null
character \0.
• The length of the string means the number of characters
between the start and the end of the string
• This length is obtained with the library function strlen().
Its prototype, in STRING.H, is
Example: size_t strlen(char *str);
• The function strlen() returns an unsigned integer
• The size_t type is used with many of the string functions.
Just remember that it means unsigned.
• The function strlen() returns the number of characters
between str and the next null character, not counting the
null character.
4
Using the strlen() function to determine
the length of a string.
#include <stdio.h>
#include <string.h>
main()
{
size_t length;
char buf[80];
while (1)
{
puts("\nEnter a line of text; a blank line terminates.");
gets(buf);
5
Contd……
length = strlen(buf);
if (length != 0)
printf("\nThat line is %u characters long.", length);
else
break;
}
return(0);
}
6
Copying Strings
7
The strcpy() Function
8
Contd..
• When using strcpy(), you must first allocate
storage space for the destination string.
• The function has no way of knowing whether
destination points to allocated space.
• If space hasn't been allocated, the function
overwrites strlen(source) bytes of memory,
starting at destination; this can cause unpredictable
problems.
9
Example of strcpy()
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char source[] = "The source string.";
main()
{
char dest1[80];
char *dest2, *dest3;
printf("\nsource: %s", source );
/* Copy to dest1 is okay because dest1 points to */
/* 80 bytes of allocated space. */
strcpy(dest1, source);
10
Contd..
11
The strncpy() Function
• The strncpy() function is similar to strcpy(), except that
strncpy() lets you specify how many characters to copy. Its
prototype is
• char *strncpy(char *destination, char *source, size_t n);
• The arguments destination and source are pointers to the
destination and source strings.
• The function copies, at most, the first n characters of
source to destination. If source is shorter than n characters,
enough null characters are added to the end of source to
make a total of n characters copied to destination.
• If source is longer than n characters, no terminating \0 is
added to destination. The function's return value is
destination.
12
The strncpy() function.
#include <stdio.h>
#include <string.h>
char dest[] = "..........................";
char source[] = "abcdefghijklmnopqrstuvwxyz";
main()
{
size_t n;
while (1)
{
puts("Enter the number of characters to copy (1-26)");
13
Contd..
scanf("%d", &n);
if (n > 0 && n< 27) break;}
printf("\nBefore strncpy destination = %s", dest);
strncpy(dest, source, n);
printf("\nAfter strncpy destination = %s\n", dest);
return(0);
}
14
The strdup() Function
15
Example:The strdup() function
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char source[] = "The source string.";
main()
{
char *dest;
16
Contd..
if ( (dest = strdup(source)) == NULL)
{
fprintf(stderr, "Error allocating memory.");
exit(1);
}
printf("The destination = %s\n", dest);
return(0);
}
17
Concatenating Strings
18
Example:The strcat() Function
#include <stdio.h>
#include <string.h>
char str1[27] = "a";
char str2[2];
main()
{
int n;
/* Put a null character at the end of str2[]. */
str2[1] = `\0';
19
Contd..
20
The strncat() Function
• The library function strncat() also performs string
concatenation, but it lets you specify how many characters
of the source string are appended to the end of the
destination string.
• The prototype is
char *strncat(char *str1, char *str2, size_t n);
If str2 contains more than n characters, the first n
characters are appended to the end of str1. If str2 contains
fewer than n characters, all of str2 is appended to the end
of str1.
• In either case, a terminating null character is added at the
end of the resulting string. You must allocate enough space
for str1 to hold the resulting string.
• The function returns a pointer to str1.
21
Example:The strncat() function
#include <stdio.h>
#include <string.h>
char str2[] = "abcdefghijklmnopqrstuvwxyz";
main()
{
char str1[27];
int n;
for (n=1; n< 27; n++)
{
strcpy(str1, "");
strncat(str1, str2, n);
puts(str1);
}
}
22
Comparing Strings
• Strings are compared to determine whether they are equal or
unequal. If they are unequal, one string is "greater than" or
"less than" the other. Determinations of "greater" and "less"
are made with the ASCII codes of the characters.
• In the case of letters, this is equivalent to alphabetical order,
with the one seemingly strange exception that all uppercase
letters are "less than" the lowercase letters. This is true
because the uppercase letters have ASCII codes 65 through 90
for A through Z, while lowercase a through z are represented
by 97 through 122.
Ex:The "ZEBRA" would be considered to be less than "apple"
by these C functions.
23
Contd..
• The ANSI C library contains functions for two types of
string comparisons: comparing two entire strings, and
comparing a certain number of characters in two strings.
• The function strcmp() compares two strings character by
character.
• Its prototype is
int strcmp(char *str1, char *str2);
24
The values returned by strcmp().
• The arguments str1 and str2 are pointers to the strings
being compared. The function's return values are given in
Table
25
Example: strcmp()
#include <stdio.h>
#include <string.h>
main()
{
char str1[80], str2[80];
int x;
while (1)
{
/* Input two strings. */
printf("\n\nInput the first string, a blank to exit: ");
gets(str1);
26
Contd..
if ( strlen(str1) == 0 )
break;
printf("\nInput the second string: ");
gets(str2);
/* Compare them and display the result. */
x = strcmp(str1, str2);
printf("\nstrcmp(%s,%s) returns %d", str1, str2, x);
}
return(0);
}
27
Searching Strings
28
The strchr() Function
29
Contd..
• When strchr() finds the character, it returns a pointer to
that character. Knowing that str is a pointer to the first
character in the string, you can obtain the position of the
found character by subtracting str from the pointer value
returned by strchr().
• Remember that the first character in a string is at position
0. Like many of C's string functions, strchr() is case-
sensitive.
• For example, it would report that the character F isn't
found in the string raffle.
30
Example: strchr()
• /*Searching for a single character with strchr().
#include <stdio.h>
#include <string.h>
main()
{
char *loc, buf[80];
int ch;
/* Input the string and the character. */
printf("Enter the string to be searched: ");
gets(buf);
31
Contd…
printf("Enter the character to search for: ");
ch = getchar();
/* Perform the search. */
loc = strchr(buf, ch);
if ( loc == NULL )
printf("The character %c was not found.", ch);
else
printf("The character %c was found at position %d.\n", ch,
loc-buf);
return(0);
}
32
The strrchr() Function
• The library function strrchr() is identical to strchr(),
except that it searches a string for the last occurrence
of a specified character in a string.
• Its prototype is
char *strrchr(char *str, int ch);
• The function strrchr() returns a pointer to the last
occurrence of ch in str and NULL if it finds no
match.
33
The strcspn() Function
• The library function strcspn() searches one string for the
first occurrence of any of the characters in a second string.
• Its prototype is
size_t strcspn(char *str1, char *str2);
• The function strcspn() starts searching at the first character
of str1, looking for any of the individual characters
contained in str2.
• The function doesn't look for the string str2, but only the
characters it contains. If the function finds a match, it
returns the offset from the beginning of str1, where the
matching character is located. If it finds no match,
strcspn() returns the value of strlen(str1).
• This indicates that the first match was the null character
terminating the string.
34
The strspn() Function
35
The strpbrk() Function
36
String Conversions
37
Contd..
• The function
strlwr() converts all the letter characters in str from
uppercase to lowercase; strupr() does the reverse,
converting all the characters in str to uppercase. Nonletter
characters aren't affected. Both functions return str.
• Note that neither function actually creates a new string but
modifies the existing string in place.
• Remember that to compile a program that uses non-ANSI
functions, you might need to tell your compiler not to
enforce the ANSI standards.
38
Miscellaneous String Functions
The strrev() Function
• The function strrev() reverses the order of all the
characters in a string.
• Its prototype is
• char *strrev(char *str);
The strset() and strnset() Functions
• The prototypes are
char *strset(char *str, int ch);
char *strnset(char *str, int ch, size_t n);
39
String-to-Number Conversions
40
The atol() Function
41
The atof() Function
42
Character Test Functions
43
lists the complete set of isxxxx() macros.
44
Contd..
• islower()Returns TRUE if ch is a lowercase letter.
• isprint()Returns TRUE if ch is a printing character
(including a space)
• .ispunct()Returns TRUE if ch is a punctuation character
• .isspace()Returns TRUE if ch is a whitespace character
(space, tab, vertical tab, line feed, form feed, or carriage
return).
• isupper()Returns TRUE if ch is an uppercase letter
• .isxdigit()Returns TRUE if ch is a hexadecimal digit (0
through 9, a through f, A through F).
45
Session Summary
• Using C standard library functions (and possibly
compiler-specific functions as well), one can copy,
concatenate, compare, and search strings.
• The standard library also contains functions for
converting the case of characters in strings and for
converting strings to numbers.
• C provides a variety of character-test functions or,
more accurately, macros that perform a variety of
tests on individual characters.
• By using these macros to test characters, one can
create their own custom input functions.
46
Thank You
47