-7

If I have a char* that is the output of another function, and I know it is one of the 10 known words, what is the best way to find what is it?

converting the char* to string bystd::string(char*) , then using string.compare() ?

char* c = "hi";
string s = std::string(c);
if (s.compare("hello") )

Is this the best way? I can not directly write:

char* c ="hi";
if(c == "hello")
Igal S.
  • 13,146
  • 5
  • 30
  • 48
Hasani
  • 3,543
  • 14
  • 65
  • 125
  • 5
    c or c++, please pick one. c has no `std::string` and in c++ why do you use a `char*` in the first place? (should be `const char*` btw) – 463035818_is_not_an_ai May 15 '18 at 11:27
  • The C way to compare strings is to use `strcmp` and alike. But before bothering about optimization, you should ask yourself if that's really the bottleneck. And on the next step, you should just try and measure it. – Jodocus May 15 '18 at 11:27
  • 2
    `std::string` has [`operator==`](http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp) defined. – Cory Kramer May 15 '18 at 11:28
  • 3
    btw to compare two `char*` as the title asks you actually do use `==`, but you dont want to compare `char*`s, you want to compare the strings pointed to by two `char*` – 463035818_is_not_an_ai May 15 '18 at 11:29
  • 5
    I think people don't read anything on some particular language and instead run to SO and expect to be educated the fundamentals of that particular language in 2 minutes. The proper answer to this should be "Read some book on C or C++". – малин чекуров May 15 '18 at 11:30
  • 1
    Question is closed due to be duplicate, but time is going and there is another option: Since C++17 you could use std::string_view to contruct "view" on C string (char*) and C++ std::string and then you could call std::string_view.compare metod. Easy and pretty fast. – ufok May 15 '18 at 11:45
  • 1
    There are plenty of "fast" methods, which might be "fastest" is impossible to tell. Why do you need the "fastest" method in any case rather the just "fast enough". With only 10 possibilities, an exhaustive comparison using `strcmp` is unlikely to be "too slow". If each possible string is unique in the first few characters, it will be faster than if they differ only in suffix characters. There are more deterministic methods that might be more useful that simply "fast". – Clifford May 15 '18 at 11:54

1 Answers1

2

Since you already have a C string, just use strcmp. It will likely be faster than the s.compare method since you avoid the overhead of doing a conversion to std::string for both the original string and the string to compare to.

if (strcmp(c, "hello") == 0) {
    ...
dbush
  • 205,898
  • 23
  • 218
  • 273