0
0
C++programming~5 mins

Character vs string comparison in C++ - Quick Revision & Key Differences

Choose your learning style9 modes available
Recall & Review
beginner
What is the difference between a character and a string in C++?
A character (char) holds a single letter or symbol, while a string (std::string) holds a sequence of characters, like a word or sentence.
Click to reveal answer
beginner
Can you compare a char and a std::string directly using == in C++?
No, you cannot directly compare a char and a std::string with == because they are different types. You must convert the char to a string or compare the char to a single character in the string.
Click to reveal answer
beginner
How do you compare a single character to the first character of a std::string?
You can compare a char variable to the first character of a string using: if (myChar == myString[0]) { ... }
Click to reveal answer
intermediate
What happens if you compare a char to a string literal using == in C++?
Comparing a char to a string literal (like 'a' == "a") is invalid because 'a' is a char and "a" is a const char array (string literal). They are different types and cannot be compared directly.
Click to reveal answer
intermediate
How can you convert a char to a std::string in C++?
You can convert a char to a std::string by using the string constructor: std::string s(1, myChar);
Click to reveal answer
Which type holds a single character in C++?
Achar
Bstd::string
Cint
Dfloat
What is the correct way to compare a char 'c' to the first character of a string 'str'?
Aif (c == str)
Bif (c == str.compare())
Cif (c == str[0])
Dif (c == str.length())
Can you directly compare a char and a std::string using ==?
AOnly if the string has one character
BNo, they are different types
CYes, always
DOnly if the char is lowercase
How do you convert a char to a std::string?
Astd::string s(1, c);
Bstd::string s = c;
Cchar s = std::string(c);
DYou cannot convert char to string
What type is a string literal like "a" in C++?
Aint
Bchar
Cstd::string
Dconst char array
Explain how to compare a single character with a string in C++.
Think about the types and how to access characters inside a string.
You got /4 concepts.
    Describe why comparing a char to a string literal directly is invalid in C++.
    Consider the types involved and what a string literal really is.
    You got /4 concepts.