Strings are a sequence of characters that represent text. In C++, the string class provides functionalities to handle and manipulate strings. It's a vital concept to grasp as a beginner. Dive into this quiz to test your knowledge and understanding of C++ strings.
1. How do you include the string library in C++?
Answer:
Explanation:
In C++, libraries are included using the #include directive, with system libraries enclosed in angle brackets < >.
2. How can you declare a string named 'greeting' with the value "Hello, World!"?
Answer:
Explanation:
The correct way to declare a string using the string class is option a). Option d) also declares a string, but it uses a character array.
3. Which member function is used to find the length of a string?
Answer:
Explanation:
The string class provides both length() and size() member functions, which return the number of characters in the string.
4. Which function is used to concatenate two strings, str1 and str2?
Answer:
Explanation:
You can use the + operator or the append() member function to concatenate two strings in C++.
5. What does the following code return?
string word = "programming";
cout << word.substr(3, 4);
Answer:
Explanation:
The substr() function returns a substring starting from the given index (3 in this case) and of the specified length (4 in this case).
6. How can you compare two strings, str1 and str2, for equality?
Answer:
Explanation:
In C++, you can use the == operator to compare two strings for equality. The compare() member function can also be used, but it returns 0 when strings are equal, not a boolean value.
7. How can you convert a string to uppercase?
Answer:
Explanation:
The transform() function from the algorithm library is used with iterators to apply the toupper() function to each character in the string.
8. Which member function removes all characters from a string?
Answer:
Explanation:
The clear() member function removes all characters from the string, making its length 0.
9. What does the following code return?
string text = "C++ Programming";
cout << text.find("Pro");
Answer:
Explanation:
The find() function returns the starting position of the first occurrence of the given substring. Indexing starts from 0.
10. If string s1 = "Hello"; and string s2 = "World";, what will be the value of s1 after s1.swap(s2);?
Answer:
Explanation:
The swap() member function swaps the contents of the two strings. So, after the swap, s1 will contain "World".
Great job on taking the quiz! Strings are fundamental in C++ programming. They provide a versatile way to handle and manipulate text. Continue practicing and diving deeper into more advanced features and functions offered by the string class in C++. Happy coding!
Comments
Post a Comment