what algorithm c ++ compares two strings? Does it make sense to write your own (more optimal)?
3 answers
Libraries lick over the years. Are you sure you can improve what many have worked on for a very long time?
But if you have additional information, a private, and not a general case - then of course. For example, you compare strings that are known to be the same in the first 10,000 characters. Or something else that may allow not to compare two memory sections in a row ...
Writing your own comparator for strings makes no sense. There are ready-made, for example string::compare :
#include <iostream> #include <string> int main () { std::string str1 ("Строка 1"); std::string str2 ("Строка 2"); if (str1.compare(str2) != 0) std::cout << str1 << " != " << str2 << '\n'; return 0; } Result:
Line 1! = Line 2
Check and you can here .
You can use C-style, for example strcmp :
#include <iostream> #include <string.h> int main () { char str1[] = "Строка 11"; char str2[] = "Строка 22"; if (strcmp(str1, str2) != 0) std::cout << str1 << " != " << str2 << '\n'; return 0; } Result:
Line 11! = Line 22
It depends on where this comparison is used.
If you compare the lines in a large document (s), then you should pay attention to the full-text search .
You should also consider substring search algorithms.