05 strings
TRANSCRIPT
-
8/10/2019 05 Strings
1/22
1
More on C++ strings
CSIS1117 Computer Programming
-
8/10/2019 05 Strings
2/22
c1117 lecture 5 2
Contents Comparing C++
strings
Simple data type char Member functions provided by C++ strings
Build-in function getline(), getchar()
-
8/10/2019 05 Strings
3/22
c1117 lecture 5 3
C++ String Recall that: C++ has a
string
library that providesmore convenient ways to handle texts.
To use the string, we need to include the header:#include
We can declarestring variables to store string values
We can assign astring constant
, or the value ofanother
string
to astring
.
We can concatenate two strings by the operator "+"
string str1 = "I loves";
string str2 = HKU";
cout "
I loves HKU :->
-
8/10/2019 05 Strings
4/22
c1117 lecture 5 4
C++ strings can also be comparedlexicographically (dictionary order) by relationaloperators. See name.cc & monthdays.cc
string str1 = "Apple"; string str2 = "apple";
string str3 = "apples"; string str4 = "orange";bool t1 = (str1 == str2);
bool t2 = (str1 < str2);
bool t3 = (str2 < str3);
bool t4 = (str3 != str4);bool t5 = (str4 > str3);
string str1 = "Apple"; string str2 = "apple";
string str3 = "apples"; string str4 = "orange";bool t1 = (str1 == str2);
bool t2 = (str1 < str2);
bool t3 = (str2 < str3);
bool t4 = (str3 != str4);bool t5 = (str4 > str3);
t1 : false
t2 : truet3 : truet4 : truet5 : true
t1 : false
t2 : truet3 : truet4 : truet5 : true
-
8/10/2019 05 Strings
5/22
c1117 lecture 5 5
Never compare two string literals directly!
At least one of the operands must be a C++str n
.
See string-cmp.cc
if("zebra" < "ant")
cout
-
8/10/2019 05 Strings
6/22
c1117 lecture 5 6
In fact, astring
is composed of a sequence ofcharacters.
Characters in a string can be specified by theirpositions. For a str n with length x, the positions of its
characters are ranging from 0 to x-1
Given astring variable
, we can access anindividual character of it using the subscriptoperator[] (square bracket).
-
8/10/2019 05 Strings
7/22
c1117 lecture 5 7
Error message may begiven if the program
accesses a character outside the range of a string.
cout
-
8/10/2019 05 Strings
8/22
c1117 lecture 5 8
Simple data type (char
)
myMsg is of type string but myMsg[4] is just acharacter!
A character is a single letter, digit, punctuation, orsymbol (mostly) can be seen on the keyboard.
string myMsg = "How are you doing?";
myMsg[4] = "d";
string myMsg = "How are you doing?";
myMsg[4] = "d";It is wrong, you will get a type mismatch error.
Can we change the characters in a string?
-
8/10/2019 05 Strings
9/22
c1117 lecture 5 9
Simple data type (char
) In C++ language, we use data type
char
torepresent characters.
char : representing value of one character
Character constants are enclosed by a pair of singlequotes, e.g. 'A', 'a', '+', '!', '9',
Non-printable characters, e.g. '\n', '\t',
Uppercase and lowercase of letters are considered to bedifferent.
-
8/10/2019 05 Strings
10/22
c1117 lecture 5 10
Simple data type (char
)
int Ival = 100; // any integers
bool Bval = true; // or falsestring Sval = "100"; // use double quotes
char Cval = '1'; // use single quotes
int Ival = 100; // any integers
bool Bval = true; // or falsestring Sval = "100"; // use double quotes
char Cval = '1'; // use single quotes
Constant value 4
How to represent the following in program?4
Constant char 4 '4'
Constant string 4 "4"
Print a new line cont
-
8/10/2019 05 Strings
11/22
c1117 lecture 5 11
Simple data type (char
) Input/output operations are similar toint and
double
.
It can be compared using relational operators.
cout choice;
cout
-
8/10/2019 05 Strings
12/22
c1117 lecture 5 12
We can change the characters in a string as follow:
string myMsg = "How are you doing?";
myMsg[0] = 'h';
cout
-
8/10/2019 05 Strings
13/22
c1117 lecture 5 13
Member functions of string The
string
library is very flexible for handingoperations related to string/text manipulation.
e.g. finding the length of a string, comparing two strings,searching/extracting of sub-string, concatenation,
Each string variable is associated with a number
of member functions, e.g.s.length ), s.substr
)
Member functions are applied to individual variableusing dot operator.
Unlike the predefined functions provided in library, e.g.sqrt ), pow )
, member functions cannot be invokedwithout a variable.
-
8/10/2019 05 Strings
14/22
c1117 lecture 5 14
Member functions of strings.length ) return the no. of characters in the
string
string s = "Hello World!";
unsigned int len_s = s.length();
cout
-
8/10/2019 05 Strings
15/22
c1117 lecture 5 15
unsigned int There are two types of int: signed and unsigned.
If neither is specified theint
issigned
.signed int
: ranging from -231 to 231-1 inclusively (inmost 32-bit CPU).
unsigned int
: only consider non-negative integers,ranging from 0 to 232-1 inclusively.
As the length of a string must be a non-negativenumber, we should use an
unsigned int
torepresent it.
unsigned int len_s = s.length();unsigned int len_s = s.length();
-
8/10/2019 05 Strings
16/22
c1117 lecture 5 16
unsigned int An overflow occurs when the result of an
arithmetic operation exceeds the representablerange.
In C++, no warning or error message will be given forinteger overflow, but incorrect result may obtained.
unsigned int x = pow(2,31) + 2;
int y = -1;
if(x > y)
cout
-
8/10/2019 05 Strings
17/22
c1117 lecture 5 17
What is the shortest length of a string?
An empty string is a string containing zero no. of
character. e.g. string s = ""
How about string r = " " ? Is it still an empty string?
See string-ex.cc as an example
No, r is a string containing one character the space
-
8/10/2019 05 Strings
18/22
c1117 lecture 5 18
Member functions of string A substring is part of a
string
. Substrings can beextracted using the member function
s.substr
)
.
s.substr(x, y) extracting a substring with length
y
starting at positionx
.
If the second argument y is omitted, a substring up to
the end of thestring
is extracted.string s (attending lecture");
string r = s.substr(0,6);
string t = s.substr(11);
string u = s.substr(11,99);
cout
-
8/10/2019 05 Strings
19/22
c1117 lecture 5 19
Member functions of string The member functions.find ) can be used to
look for the occurrence of one string in another. s.find(r) checking if string r occurs in the string s.
The starting position of the first occurrence is reported.
If there is no such occurrence, the constant
string::npos
defined in is returned.
string r = "programming";
int a = r.find("gram");
cout
-
8/10/2019 05 Strings
20/22
c1117 lecture 5 20
Reading a line from input We use cin >> v1 >> v2 >> >> vn to get data
from input.
cin makes use of whitespace characters as inter-data separator. So
cin
will skip all the whitespacesyou typed. See cin-input.cc as an example.
As a result, we cannot read a string involvingspace character into a
string variable
.
-
8/10/2019 05 Strings
21/22
c1117 lecture 5 21
Instead, we can use the library functiongetline() to read a line from the current
position till the end of the current line.
See read-a-line.cc for an example.
string s;
getline(cin, s);
cout
-
8/10/2019 05 Strings
22/22
c1117 lecture 5 22
Reading characters from input Similarly, if we want to read characters one by one
from input, including the whitespace characters,we can use the library function
getchar )
.
char a, b, c;
cout