Part 5 - String class, Files and Streams, C++ vs Java Flashcards
WHat will
string s4(5, ‘x’);
do?
Make a string with 5 ‘x’ s i.e.
“xxxxx”
What does the .at method do in strings?
What is the implication of this?
Returns a reference to the character at that position
Can do
s.at(2) = ‘e’;
What does the append function do to strings?
s1.append(s2) will append s2 to the end of s1
same as +=
What will s2.append(3, ‘!’);
do?
append 3 !s to the end of s2
Demonstrate substrings, replacing strings and erasing parts of strings
s1. substr(m, n) will get a copy of the string n characters long starting at m
s1. replace(m, n, x) will replace substring or length n starting at m with a copy x
s1. erase(m, n) will erase n characters starting with m
How do the < <= > and >= operators compare strings?
Lexicographically using ASCII ordering
what does the compare function do with strings?
s1.compare(s2) returns 0 if they are equal, negative number if s1 is before s2 and positive number of s2 is before s1
What will the find and rfind functions do with strings?
s. find(‘l’) finds the index of the first instance of l in the string s
s. rfind finds the index of the last instance of l in the string s
if l is not found string::npos is returned
What is the second argument that can optionally be used with the find or rfind functions on the string class?
start index
Write a function to count the number of instances of a given character in a string
int count(string s, char c) {
int tot = 0;
int pos = s.find(c);
while (pos != string::npos) {
tot++;
pos = s.find(c);
}
return tot;
}
What do the find_first_of and find_first_not_of functions do?
s. find_first_of(“ \t\n”) finds the first white space character
s. find_first_not_of(“ \t\n”) finds the first non whitespace character
What is the getline function used for? How is it used?
To get a line of text that may contain whitespace
Takes reference to a stream and reference to string where result will be stored, e.g.
getline(cin, s2)
What are the benefits of a string stream?
Input and output to be performed to and from string objects
Formatting like setw and setfill can be used
What class and header can be used for an output string stream?
Give an example of a method to output something using one
<sstream></sstream>
ostringstream
void fun(string s) {
ostringstream os;
os << setfill(‘0’) << setw(10) << s;
return os.str();
}
Give an example using istringstream to convert a string to an int
int stoi2(string s) {
istringstream str(s);
int i;
str >> i;
return i;
}