Sie sind auf Seite 1von 42

Problem Solving & Programming II C++ Programming

String C-string values and variables Character manipulating functions

A STRING is a null terminated (\0 sentinel string character ) array of characters A new data type is now considered, namely, the character string, which is used to represent a sequence of characters regarded as a single data item. In C++ strings of characters are held as an array of characters, one character held in each array element. In addition a special null character, represented by `\0', is appended to the end of the string to indicate the end of the string. strings are defined as an array of characters or a pointer to a portion of memory containing ASCII characters. A string in C is a sequence of zero or more characters followed by a NULL ( )character: Header file : <string.h>

The Sentinel String Character '\0'


For example, the following two arrays both contain all the characters in the string value ""Enter age: "", but only the array on the left contains a proper string representation.

NOTE: although both "phrase" and "list" are arrays of characters, only "phrase" is big enough to contain the string value ""Enter age: "". We don't care what characters are stored in the variables "phrase[12]" and "phrase[13]", because all the string functions introduced below ignore characters after the "'\0'".

A string variable s1 could be declared as follows: char s1[10]; The string variable s1 could hold strings of length up to nine characters since space is needed for the final null character. Strings can be initialised at the time of declaration just as other variables are initialised. For example: char s1[] = "example"; char s2[20] = "another example" would store the two strings as follows: s1 |e|x|a|m|p|l|e|\0| s2 |a|n|o|t|h|e|r| |e|x|a|m|p|l|e|\0|?|?|?|?|
NOTE:In the first case the array would be allocated space for eight characters, that is space for the seven characters of the string and the null character. In the second case the string is set by the declaration to be twenty characters long but only sixteen of these characters are set, i.e. the fifteen characters of the string and the null character. Note that the length of a string does not include the terminating null character.

String Variable Declarations and Assignments


String variables can be declared just like other arrays: char phrase[14]; String arrays can be initialised or partially initialised at the same time as being declared, using a list of values enclosed in "{}" braces (the same is true of arrays of other data types). For example, the statement

char phrase[14] = {'E','n','t','e','r',' ','a','g','e',':',' ','\0'}; char phrase[14]=Enter Integer:

Or char phrase[ ] = {'E','n','t','e','r',' ','a','g','e',':',' ','\0'};


char phrase[ ]=Enter Integer: Or char phrase[12] = {'E','n','t','e','r',' ','a','g','e',':',' ','\0'};

puts
output used for the strings/special output for
string syntax: puts(<variable>);

gets
input used for the strings/special input for strings

syntax: gets(<variable>);

NOTE: header file for input/output for string is <stdio.h>

cout
output used for the strings/special output for
string syntax: cout<<string;

cin.getline
input used for the strings/special input for strings

syntax: cin.getline(<string var>, <no. characters>);


example: cin.getline(myString,20)

The string Class


Class: a user-created data type that defines a valid set of data values and a set of operations that can be used on them Object: storage area declared for a class string class permits string literals String literal: any sequence of characters enclosed in double quotation marks; also called string value, string, constant
Figure 7.1 The storage of a string as a sequence of characters.

C++ for Engineers and Scientists, Second Edition

The string Class (continued)


string class provides functions for declaring, creating, and initializing a string Methods: functions in a class Constructor: the method which creates and initializes a string object string header file is required to use the string class

C++ for Engineers and Scientists, Second Edition

The string Class (continued)

C++ for Engineers and Scientists, Second Edition

10

The string Class (continued)

C++ for Engineers and Scientists, Second Edition

11

The string Class (continued)


Character positions within a string are numbered starting with zero

C++ for Engineers and Scientists, Second Edition

12

The string Class (continued)


Strings can be input from the keyboard and displayed on the screen using cout, cin, and getline getline continuously accepts and stores characters from the keyboard until the terminating key is pressed If the last argument is omitted, the Enter key will terminate the input
Syntax:

getline(cin, strObj, terminatingChar)


C++ for Engineers and Scientists, Second Edition 13

The string Class (continued)

C++ for Engineers and Scientists, Second Edition

14

The string Class (continued)


Using cin and getline inputs together in the same program may cause problems cin accepts the input, but leaves the newline code from the Enter key in the buffer, which will be picked up by the getline as the end of its input

C++ for Engineers and Scientists, Second Edition

15

The string Class (continued)


Three possible solutions to this problem:
Do not use cin and getline inputs in the same program Follow the cin input with cin.ignore() Accept the Enter key into a character variable and then ignore it

C++ for Engineers and Scientists, Second Edition

16

The string Class (continued)


string class provides many methods for manipulating strings, including
length: returns the length of the string at: returns the character at the specified index compare: compares two strings empty: tests if the string is empty erase: removes characters from the string find: returns the index of the first occurrence of a string in an object

C++ for Engineers and Scientists, Second Edition

17

The string Class (continued)


string class methods (continued):
insert: inserts one string into another string at the specified index replace: replaces characters in an object at the specified index substr: returns a portion of a string swap: swaps characters in a string with a specified object

Concatenation operator (+) combines two strings


C++ for Engineers and Scientists, Second Edition 18

The string Class (continued)


All relational operators may be used to compare strings; ASCII or UNICODE code values are used for comparison

Figure 7.5 The initial strings used in Program 7.6.


C++ for Engineers and Scientists, Second Edition 19

The string Class (continued)

C++ for Engineers and Scientists, Second Edition

20

The string Class (continued)

C++ for Engineers and Scientists, Second Edition

21

The string Class (continued)


Example: Inserting characters in a string
string str = This cannot be;

str.insert(4, I know);

C++ for Engineers and Scientists, Second Edition

22

The string Class (continued)


Example: Replacing characters in a string
str.replace(12, 6, to);

str += correct;

C++ for Engineers and Scientists, Second Edition

23

The string Class (continued)

C++ for Engineers and Scientists, Second Edition

24

strcpy( )
- used to copy the content of string2 into string1 Syntax: strcpy(string1,string2)

Example: The following code fragment copies hello into string1

main()
{ char string1[8]; strcpy(string1,hello); . . }

strcat( )
- concatenates a copy of string2 to string1 with a null. The string is untouched by the operation Syntax: strcat(string1,string2) Example: this program appends the first string inputted to the second string inputted. For example assuming the user enters hello and there, the program will pring hellothere.

main() {

char string1[8],string2[8];
gets(string1); gets(string2); strcat(string1,string2); puts(string1);

.
. }

strcmp( )
- lexicographically compares two null terminated strings.
Syntax: (strcmp(string1,string2)(<,>,= =)0) Related Function: strcmpi(),stricmp(),strcoll() Value <0 Meaning string1 is less than string2

>0
= =0

string1 is greater than string2


string1 is equal to string2

strcspn( )
- returns the index or the subscript of the first character in the string pointed to by string1 that matches any of the characters in the string pointed to by string2. Syntax: strcspn(string1,string2)

Example: This program prints the number 8.


main() { int length; length=strcspn(this is a test,a) cprintf(%i,length);}

strlen( )
Syntax: strlen(string1)

- returns the length of a null terminated string pointed to by string

Example: This program prints the number 4 if the entered value of string1 isRHEN. main() { char string1[20]; gets(string1); printf(%i,strlen(string1));}

strlwr( )
- converts the string pointed to by string1 to lowercase

Related Function: strupr()


Syntax: strlwr(string1) Example: This program prints merry christmas on the screen. main() { char string1[50]; strcpy(string1,MERRY CHRISTMAS); strlwr(string1); printf(string1));}

strncpy( )

- used to copy up to count characters from the string pointed to by source into the string pointed to by destination, the source must be a pointer to a null terminated string. Syntax: strncpy(string1,string2)

Example: The following code fragment copies at most 79 characters of string1 into string2, thus ensuring that no array boundaries overflow will occur.
Main() { char string1[120],string2[80]; gets(string1); strncpy(string2,string1,79);}

strrev( )
- reverses all the characters, except the null terminator, in the string pointed to by str. It returns str. Syntax: strrev(string) Example: This programs prints hello backwards on the screen.
Main() { char s[ ]=hello; strrev(s); printf(s); return 0; }

Character Manipulation Methods


Character manipulation methods require the header file string or cctype character class provides methods for character manipulation, including
Character type detection: isalpha, isalnum, isdigit, isspace, isprint, isascii, isctrl, ispunct, isgraph, isupper, islower Character case conversion: toupper, tolower
C++ for Engineers and Scientists, Second Edition 34

Character Manipulation Methods (continued)

C++ for Engineers and Scientists, Second Edition

35

Character Manipulation Methods (continued)


Basic character I/O methods, requiring the header file cctype, include
cout.put: put a character on the output stream cin.get: extract a character from the input stream cin.peek: assign the next character from the input stream to a variable without extracting it cin.putback: pushes a character back onto the input stream cin.ignore: ignores input characters
C++ for Engineers and Scientists, Second Edition 36

Character Manipulation Methods (continued)


When a character is requested after the user has already input some other data, get() method may pick up the Enter key instead of the new data Two ways to solve this problem:
Use a cin.ignore() after the cin.get() Accept Enter key and do not process it

C++ for Engineers and Scientists, Second Edition

37

Character Manipulation Methods (continued)

C++ for Engineers and Scientists, Second Edition

38

Input Data Validation


User-input validation includes checking each entered character to ensure it is the expected data type Can accept user input as a string, and then check each character for proper type
Example: input of an integer number Data must contain one or more characters If the first character is a + or -, there must be at least one digit Only digits from 0 to 9 are acceptable
C++ for Engineers and Scientists, Second Edition 39

Common Programming Errors


Failure to include the string header file when using string class objects Failure to remember that the newline character, \n, is a valid data input character Failure to convert a string class object using the c_str() method when converting to numerical data types

C++ for Engineers and Scientists, Second Edition

42

Summary
String literal: any sequence of characters enclosed in double quotation marks string class can be used to construct a string string class objects are used when comparing, searching, examining, or extracting a substring, or replacing, inserting, or deleting characters cin object terminates input when a blank is encountered
C++ for Engineers and Scientists, Second Edition 43

Summary (continued)
getline() method can be used for string class data input cout object can be used to display string class strings

C++ for Engineers and Scientists, Second Edition

44

Das könnte Ihnen auch gefallen