Having this code:
char a[20]="wasd", b[20]="asd";
if((a+1)==b)
printf("yes");
Will not return "yes", even if "a+1" is "asd". I am wondering what am I doing wrong?
You need to use strcmp to compare C strings. == will just compare the pointers.
For example:
#include <string.h> // or <cstring> if you're writing C++
...
char a[20]="wasd", b[20]="asd";
if(strcmp(a+1, b)==0)
printf("yes");
By the way, if you're writing C++, you'd be better off using std::string. Then you could have simply used == to compare them.
std::string. Then you could have simply used == to compare them.If it's not a student assignment and you truly are using C++(as your tag says) you should use strings. Now you're using arrays and comparing arrays addresses instead of real strings. In a C++ way your code might look like:
#include <iostream>
#include <string>
int main()
{
std::string a ="wasd";
std::string b ="asd";
if(a.substr(1) == b)
std::cout << "Yes!\n";
}
Well, there is a better way to find if one string contains another but the code is a direct mapping of your C code to the C++-ish one.
You are actually comparing pointer addresses, not the actual string contents.
Your code should use strcmp:
char a[20]="wasd", b[20]="asd";
if(strcmp(a+1, b) == 0)
printf("yes");
Be careful that strcmp returns 0 if the strings are identical.
A better and more idiomatic alternative would be to use std::string:
std::string a = "wasd", b = "asd";
if(a.substr(1) == b)
std::cout << "yes";
substr does copy the string though, so it is slightly less efficient than the previous approach.
As per your code, when using (a+1)==b you are comparing the addresses of the pointers pointing respectively to second character of string 'a' and the first character of string 'b'.
It can work if you modify your code as:
char a[20]="wasd", b[20]="asd";
if(*(a+1)==*b) // now we are comparing the values towards which the
printf("yes"); // respective pointers are pointing
You can also use compare() for comparison of strings included in .
std::string) rather than old skool Cchar *s - that way you can just use==to test for equality rather than calling C library functions such asstrcmp.