Answer the question
In order to leave comments, you need to log in
How to compare two strings of type string?
I implement the algorithm for quick sorting of strings
. There is an array of term string Str[100];
there is a variable string Str2
how can they be compared like this, an example of comparing type int
int s_arr[100];
int x = 8;
while (s_arr[i] < x) i++;
while (s_arr[j] > x) j--;
Answer the question
In order to leave comments, you need to log in
std::string arr[] = {"123", "abc", "@$%"};
std::string str = "Hello";
while (s_arr[i] < x) i++;
while (s_arr[j] > x) j--;
The compare() method is defined for class basic_string.
And through it, the friend operators ==, |=, >, <, <=, >= are redefined.
All operations can be applied to both string and const char* as one of the operands.
The meaning of the comparisons is the natural lexographic order, which you ( easily ) cannot change.
As a rule, overloaded comparison operators <, >, ==, etc. are already available for all classes that implement work with strings (CString, std::string, QString). There may also be conditional comparison methods, such as CompareNoCase.
If you are implementing a quicksort algorithm and want to implement your own string comparison methods, then the simplest option is to inherit from the string class and override the comparison methods.
If you are working with char* then see the implementation of memmcmp and strcmp
www.cplusplus.com/reference/cstring/memcmp
www.cplusplus.com/reference/cstring/strcmp
PS advice, do not reinvent the wheel, because. sorting algorithms have been honed by mathematicians and programmers for many years. You can only feel the performance benefit if you have very specific string sets.
For example, for all strings, the first three characters are the same, then custom sorting from the 4th character can give a gain in time.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question