Which header file is required to use the `std::string` class in C++?
A
<string.h> B
<cstring> C
<string> D
<stdlib.h>
Analysis & Theory
In C++, the `std::string` class is defined in the `<string>` header.
Which of the following correctly declares a string in C++?
A
string name = 'John'; B
string name = "John"; C
char name = "John"; D
string name('John');
Analysis & Theory
Double quotes are used for string literals in C++, so `"John"` is valid.
What will be the output of: `std::string s = "Hello"; std::cout << s.length();`?
A
4 B
5 C
6 D
Error
Analysis & Theory
`s.length()` returns the number of characters in the string, which is 5 for "Hello".
Which of the following is used to concatenate two strings `a` and `b`?
A
a.concat(b) B
a + b C
a.append(b) D
Both b and c
Analysis & Theory
`+` and `.append()` both can be used to concatenate strings in C++.
Which method removes all characters from a string?
A
clear() B
erase() C
remove() D
empty()
Analysis & Theory
`clear()` empties the string completely.
What does the `empty()` function return for an empty string?
A
false B
true C
0 D
Segmentation fault
Analysis & Theory
`empty()` returns true if the string has no characters.
Which of the following gets a full line of input including spaces?
A
cin >> str; B
getline(cin, str); C
scanf("%s", str); D
cin.get(str);
Analysis & Theory
`getline(cin, str);` reads an entire line including spaces.
What is the result of `s.substr(1, 3)` where `s = "program"`?
A
"rog" B
"ogr" C
"rogra" D
"gram"
Analysis & Theory
`substr(1, 3)` returns a substring starting at index 1 of length 3, which is "rog".
How can you compare two strings `a` and `b` in C++ for equality?
A
a == b B
a.compare(b) == 0 C
strcmp(a, b) D
Both a and b
Analysis & Theory
In C++, you can use `==` or `compare()` method. `strcmp()` is used for C-style strings.
What does `s.at(2)` return for `s = "hello"`?
A
'e' B
'l' C
'o' D
'h'
Analysis & Theory
Indexing starts from 0. `s.at(2)` is the third character, which is 'l'.