string s;
s += '\0';
s += '\t';
if (s == "\0\t")
cout << "Yahoo";
I can't get "yahoo".
And does it mean that if I want to check string like this, I have to code like this?
if (s[0] == '\0' && s[1] == '\t')
cout << "Yahoo";
'\0' is referred to as NULL character or NULL terminator It is the character equivalent of integer 0(zero) as it refers to nothing. In C language it is generally used to mark an end of a string.
Note: When comparing two strings in java, we should not use the == or != operators. These operators actually test references, and since multiple String objects can represent the same String, this is liable to give the wrong answer.
The \0 is treated as NULL Character. It is used to mark the end of the string in C. In C, string is a pointer pointing to array of characters with \0 at the end.
You are using the operator which compares a std::string
with a const char*
. In that function, the const char*
is assumed to be pointing to a null-terminated (i.e. '\0'
) c-string. Since the '\t'
comes after the terminator, the function does not consider it as part of the string, and in fact, would have no good way of even being able to figure out that it was there.
You could do this:
if (s == std::string("\0\t",2))
That will construct a std::string
with the full string literal (minus the terminating '\0'
that the compiler adds), and will compare your string with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With