Download - Week 5 6- String
-
7/29/2019 Week 5 6- String
1/42
Problem Solving &Programming II
C++ ProgrammingStringC-string values and variables
Character manipulating functions
-
7/29/2019 Week 5 6- String
2/42
- 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 arrayelement. 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 :
-
7/29/2019 Week 5 6- String
3/42
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'".
-
7/29/2019 Week 5 6- String
4/42
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.
-
7/29/2019 Week 5 6- String
5/42
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 asbeing 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'};
-
7/29/2019 Week 5 6- String
6/42
putsoutput used for the strings/special output for
string
syntax: puts();
gets
input used for the strings/special input for strings
syntax: gets();
NOTE: header file for input/output for string is
-
7/29/2019 Week 5 6- String
7/42
coutoutput used for the strings/special output for
string
syntax: cout
-
7/29/2019 Week 5 6- String
8/42
C++ for Engineers and Scientists, Second Edition 8
The string Class
Class: a user-created data type that defines avalid set of data values and a set of operationsthat 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 calledstring value, string, constant
Figure 7.1 The
storage of a string
as a sequence of
characters.
-
7/29/2019 Week 5 6- String
9/42
C++ for Engineers and Scientists, Second Edition 9
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 andinitializes a string object
string header file is required to use the
string class
-
7/29/2019 Week 5 6- String
10/42
C++ for Engineers and Scientists, Second Edition 10
The string Class (continued)
-
7/29/2019 Week 5 6- String
11/42
C++ for Engineers and Scientists, Second Edition 11
The string Class (continued)
-
7/29/2019 Week 5 6- String
12/42
C++ for Engineers and Scientists, Second Edition 12
The string Class (continued)
Character positions within a string are
numbered starting with zero
-
7/29/2019 Week 5 6- String
13/42
C++ for Engineers and Scientists, Second Edition 13
The string Class (continued)
Strings can be input from the keyboard anddisplayed on the screen using cout,cin, andgetline
getline continuously accepts and storescharacters from the keyboard until theterminating key is pressed
If the last argument is omitted, the Enter key
will terminate the inputSyntax:
getline(cin, strObj, terminatingChar)
-
7/29/2019 Week 5 6- String
14/42
C++ for Engineers and Scientists, Second Edition 14
The string Class (continued)
-
7/29/2019 Week 5 6- String
15/42
C++ for Engineers and Scientists, Second Edition 15
The string Class (continued)
Using cin and getline inputs together in thesame program may cause problems
cin accepts the input, but leaves the newline
code from the Enter key in the buffer, which willbe picked up by the getline as the end of its
input
-
7/29/2019 Week 5 6- String
16/42
C++ for Engineers and Scientists, Second Edition 16
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
-
7/29/2019 Week 5 6- String
17/42
C++ for Engineers and Scientists, Second Edition 17
The string Class (continued)
string class provides many methods formanipulating 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 ofa string in an object
-
7/29/2019 Week 5 6- String
18/42
C++ for Engineers and Scientists, Second Edition 18
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
-
7/29/2019 Week 5 6- String
19/42
C++ for Engineers and Scientists, Second Edition 19
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.
-
7/29/2019 Week 5 6- String
20/42
C++ for Engineers and Scientists, Second Edition 20
The string Class (continued)
-
7/29/2019 Week 5 6- String
21/42
C++ for Engineers and Scientists, Second Edition 21
The string Class (continued)
-
7/29/2019 Week 5 6- String
22/42
C++ for Engineers and Scientists, Second Edition 22
The string Class (continued)
Example: Inserting characters in a string
string str = This cannot be;
str.insert(4, I know);
-
7/29/2019 Week 5 6- String
23/42
C++ for Engineers and Scientists, Second Edition 23
The string Class (continued)
Example: Replacing characters in a stringstr.replace(12, 6, to);
str += correct;
-
7/29/2019 Week 5 6- String
24/42
C++ for Engineers and Scientists, Second Edition 24
The string Class (continued)
-
7/29/2019 Week 5 6- String
25/42
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);
.
. }
-
7/29/2019 Week 5 6- String
26/42
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.
-
7/29/2019 Week 5 6- String
27/42
main()
{
char string1[8],string2[8];
gets(string1);
gets(string2);
strcat(string1,string2);
puts(string1);
.
.
}
-
7/29/2019 Week 5 6- String
28/42
strcmp( )
- lexicographically compares two null terminated strings.
Syntax: (strcmp(string1,string2)(,= =)0)
Related Function: strcmpi(),stricmp(),strcoll()
Value Meaning
< 0 string1 is less than string2>0 string1 is greater than string2
= =0 string1 is equal to string2
-
7/29/2019 Week 5 6- String
29/42
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);}
-
7/29/2019 Week 5 6- String
30/42
strlen( )- returns the length of a null terminated string pointed to by strin
Syntax: strlen(string1)
Example: This program prints the number 4 if the entered valu
of string1 isRHEN.
main()
{ char string1[20];
gets(string1);
printf(%i,strlen(string1));}
-
7/29/2019 Week 5 6- String
31/42
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));}
-
7/29/2019 Week 5 6- String
32/42
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);}
-
7/29/2019 Week 5 6- String
33/42
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;
}
-
7/29/2019 Week 5 6- String
34/42
C++ for Engineers and Scientists, Second Edition 34
Character Manipulation Methods
Character manipulation methods require theheader file string orcctype
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
Character Manipulation Methods
-
7/29/2019 Week 5 6- String
35/42
C++ for Engineers and Scientists, Second Edition 35
Character Manipulation Methods
(continued)
-
7/29/2019 Week 5 6- String
36/42
C++ for Engineers and Scientists, Second Edition 36
Character Manipulation Methods
(continued)
Basic character I/O methods, requiring theheader file cctype, include
cout.put: put a character on the output stream
cin.get: extract a character from the inputstream
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
-
7/29/2019 Week 5 6- String
37/42
C++ for Engineers and Scientists, Second Edition 37
Character Manipulation Methods
(continued)
When a character is requested after the userhas 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
-
7/29/2019 Week 5 6- String
38/42
C++ for Engineers and Scientists, Second Edition 38
Character Manipulation Methods
(continued)
-
7/29/2019 Week 5 6- String
39/42
C++ for Engineers and Scientists, Second Edition 39
Input Data Validation
User-input validation includes checking eachentered character to ensure it is the expected
data type
Can accept user input as a string, and thencheck 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
-
7/29/2019 Week 5 6- String
40/42
C++ for Engineers and Scientists, Second Edition 42
Common Programming Errors
Failure to include the string header file whenusing string class objects
Failure to remember that the newline
character, \n, is a valid data input character
Failure to convert a string class object usingthe c_str() method when converting to
numerical data types
-
7/29/2019 Week 5 6- String
41/42
C++ for Engineers and Scientists, Second Edition 43
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
-
7/29/2019 Week 5 6- String
42/42
Summary (continued)
getline() method can be used forstring
class data input
cout object can be used to display string
class strings