A. Hello World
B. Hello
C. World
D. Error
Answer: B
Explanation:
char* are terminated by a ‘\0’ character so the string “Hello\0World” will be cut down to “Hello”.
2. What will be the output of the following C++ code?
#include
#include
#include
using namespace std;
int main(int argc, char const *argv[])
{
string s("a");
cout<
A. a
B. empty string
C. Error
D. Segmentation fault
Answer: A
Explanation:
string class has a constructor for this call hence the string s will be assigned “a”.
3. What will be the output of the following C++ code?
#include
#include
#include
using namespace std;
int main()
{
string s('a');
cout<
A. a
B. empty string
C. Error
D. Segmentation fault
Answer: C
Explanation:
The string class provides string(string s) as a constructor not the string(char) as a constructor therefore this assignment is not valid.
4. Which is the correct way of concatenating a character at the end of a string object?
way 1:
string s;
s = s + 'a';
way 2:
string s;
s.push_back('a');
A. 1 only
B. 2 only
C. both of them
D. both are wrong
Answer: C
Explanation:
string class provides the addition of char and string and also push_back(char) function to append a character at the end of a string.
5. What will be the output of the following C++ code?
#include
#include
using namespace std;
int main ()
{
std::string str ("Sanfoundry.");
str.back() = '!';
std::cout << str << endl;
return 0;
}
A. Sanfoundry.!
B. Sanfoundry.
C. Sanfoundry!
D. Sanfoundry!.
Answer: C
Explanation:
back() function modifies the last character of the string with the character provided.
6. What will be the output of the following C++ code?
#include
#include
using namespace std;
int main ()
{
string str ("sanfoundry.");
str.front() = 'S';
cout << str << endl;
return 0;
}
A. Sanfoundry
B. Sanfoundry.
C. sanfoundry
D. sanfoundry.
Answer: B
Explanation:
front() modifies the first character of the string with the character provided.
7. What will be the output of the following C++ code?
#include
#include
using namespace std;
int main ()
{
string str ("sanfoundry.");
cout << str.substr(3).substr(4) << endl;
return 0;
}
A. foundry.
B. dry.
C. oundry.
D. found
Answer: B
Explanation:
As we are first taking the substring of s from 3 to end then on that substring we are taking substr from 4 to end which is equal to “dry.”.
8. What will be the output of the following C++ code?
#include
#include
using namespace std;
int main ()
{
string str = "Sanfoundry!";
cout<
A. 1511
B. 1111
C. 1115
D. 010
Answer: A
Explanation:
Capacity of a string object is defined as the length of string plus the extra space given to that object which will be used further if string is expanded.