+ All Categories
Home > Documents > C-Programming-Class 9

C-Programming-Class 9

Date post: 12-Nov-2014
Category:
Upload: jackharish
View: 219 times
Download: 0 times
Share this document with a friend
47
1 Session 09 Manipulating Strings
Transcript

1

Session 09

Manipulating Strings

2

Session Objectives

• How to determine the length of a string • How to copy and join strings • About functions that compare strings • How to search strings • How to convert strings • How to test characters

3

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

4

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.

5

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);

6

Contd……length = strlen(buf); if (length != 0) printf("\nThat line is %u characters long.", length); else break;} return(0);}

7

Copying Strings

• The C library has three functions for copying strings.

• A copy the source string from its location in memory to the memory location of the destination string.

• The string-copying functions are strcpy(), strncpy(), and strdup().

• All of the string-copying functions require the header file STRING.H.

8

The strcpy() Function

• The library function strcpy() copies an entire string to another memory location.

• Its prototype is as follows: char *strcpy( char *destination, char *source ); • The function strcpy() copies the string (including the

terminating null character \0) pointed to by source to the location pointed to by destination.

• The return value is a pointer to the new string, destination.

9

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.

10

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);

11

Contd..

printf("\ndest1: %s", dest1); /* To copy to dest2 you must allocate space. */ dest2 = (char *)malloc(strlen(source) +1); strcpy(dest2, source); printf("\ndest2: %s\n", dest2); /*Copying without allocating destination space is a no-no. */ /* The following could cause serious problems. */ /* strcpy(dest3, source); */ return(0); }

12

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.

13

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)");

14

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);

}

15

The strdup() Function

• The library function strdup() is similar to strcpy(), except that strdup() performs its own memory allocation for the destination string with a call to malloc().

• The prototype for strdup() ischar *strdup( char *source );

• The argument source is a pointer to the source string. The function returns a pointer to the destination string--the space allocated by malloc()--or NULL if the needed memory couldn't be allocated.

16

Example:The strdup() function

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

char source[] = "The source string.";

main()

{

char *dest;

17

Contd..

if ( (dest = strdup(source)) == NULL)

{

fprintf(stderr, "Error allocating memory.");

exit(1);

}

printf("The destination = %s\n", dest);

return(0);

}

18

Concatenating Strings

• Concatenating Strings means to join two strings--to tack one string onto the end of another--and, in most states, it is legal.

• The C standard library contains two string concatenation functions--strcat() and strncat()--both of which require the header file STRING.H.

• The function appends a copy of str2 onto the end of str1, moving the terminating null character to the end of the new string.

• You must allocate enough space for str1 to hold the resulting string. The return value of strcat() is a pointer to str1.

19

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';

20

Contd..

for (n = 98; n< 123; n++) {str2[0] = n; strcat(str1, str2); puts(str1);} return(0);}

21

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.

22

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);}}

23

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.

24

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);

25

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

Return Value Meaning

< 0 str1 is less than str2.

0 str1 is equal to str2.

> 0 str1 is greater than str2.

26

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);

27

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);}

28

Searching Strings

• The C library contains a number of functions that search strings.

• These functions determine whether one string occurs within another string and, if so, where. You can choose from six string-searching functions, all of which require the header file STRING.H

29

The strchr() Function

• The strchr() function finds the first occurrence of a specified character in a string.

• The prototype ischar *strchr(char *str, int ch);

• The function strchr() searches str from left to right until the character ch is found or the terminating null character is found. If ch is found, a pointer to it is returned. If not, NULL is returned.

30

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.

31

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);

32

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);}

33

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.

34

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 issize_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.

35

The strspn() Function

• This function is related to the previous one, strcspn(), as the following paragraph explains.

• Its prototype issize_t strspn(char *str1, char *str2);

• The function strspn() searches str1, comparing it character by character with the characters contained in str2. It returns the position of the first character in str1 that doesn't match a character in str2.

• The strspn() returns the length of the initial segment of str1 that consists entirely of characters found in str2. The return is 0 if no characters match.

36

The strpbrk() Function

• The library function strpbrk() is similar to strcspn(), searching one string for the first occurrence of any character contained in another string. It differs in that it doesn't include the terminating null characters in the search.

• The function prototype ischar *strpbrk(char *str1, char *str2);

• The function strpbrk() returns a pointer to the first character in str1 that matches any of the characters in str2. If it doesn't find a match, the function returns NULL. NULL, of course).

37

String Conversions

• The many C libraries contain two functions that change the case of characters within a string.

• These functions aren't ANSI standard and therefore might differ or not even exist in your compiler. Because they can be quite useful, they are included here. Their prototypes, in STRING.H, are as follows for the Microsoft C compiler (if you use a different compiler, they should be similar):

char *strlwr(char *str); char *strupr(char *str);

38

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.

39

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);

40

String-to-Number Conversions

• The atoi() Function

• The library function atoi() converts a string to an integer.

• The prototype is

int atoi(char *ptr);

• The function atoi() converts the string pointed to by ptr to an integer.

41

The atol() Function

• The library function atol() works exactly like atoi(), except that it returns a type long.

• The function prototype is

long atol(char *ptr);

42

The atof() Function

• The function atof() converts a string to a type double. • The prototype is

double atof(char *str); • The argument str points to the string to be converted. This

string can contain leading white space and a + or -- character.

• The number can contain the digits 0 through 9, the decimal point, and the exponent indicator E or e. If there are no convertible characters, atof() returns 0.

43

Character Test Functions

• The header file CTYPE.H contains the prototypes for a number of functions that test characters, returning TRUE or FALSE depending on whether the character meets a certain condition.

• For example, is it a letter or is it a numeral? The isxxxx() functions are actually macros, defined in CTYPE.H.

The isxxxx() macros all have the same prototype:• int isxxxx(int ch); In the preceding line, ch is the character

being tested. The return value is TRUE (nonzero) if the condition is met or FALSE (zero) if it isn't.

44

lists the complete set of isxxxx() macros.

• isalnum()Returns TRUE if ch is a letter or a digit• .isalpha()Returns TRUE if ch is a letter.• isascii()Returns TRUE if ch is a standard ASCII

character (between 0 and 127).• iscntrl()Returns TRUE if ch is a control character.• isdigit()Returns TRUE if ch is a digit• .isgraph()Returns TRUE if ch is a printing

character (other than a space).

45

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).

46

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.

47

Thank You


Recommended