Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a string which contains '\0' and '\t' can't use operator == to compare with "\0\t"?

Tags:

c++

string

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";
like image 971
Huang-zh Avatar asked Jul 23 '14 05:07

Huang-zh


People also ask

What is the meaning of \0 in string?

'\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.

Can we use != For 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.

What is the mean of \0 in C++?

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.


1 Answers

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.

like image 91
Benjamin Lindley Avatar answered Sep 18 '22 06:09

Benjamin Lindley