string sorting

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
How are strings sorted?
They are compared with ascii
but sometimes the total ascii value can be the same but rearranged differently

How I would tackle this problem is that I check the the string starts with a 1 and then sort that way.
1
2
3
...
...
...
69

but that is too long, i have iterate thru the whole file convert string into ascii and then compare.
Strings are compared lexicographically.
cppreference wrote:
Lexicographical comparison is a operation with the following properties:
- Two ranges are compared element by element.
- The first mismatching element defines which range is lexicographically less or greater than the other.
- If one range is a prefix of another, the shorter range is lexicographically less than the other.
- If two ranges have equivalent elements and are of the same length, then the ranges are lexicographically equal.
- An empty range is lexicographically less than any non-empty range.
- Two empty ranges are lexicographically equal.

https://en.cppreference.com/w/cpp/algorithm/lexicographical_compare

That page describes a more general comparision, but in this specific case, the term range can be read to mean string. The results of such a comparison generally (but not necessarily) corresponds to dictionary order, or something close to it.

The C++ standard library uses this comparison when comparing two objects of type std::string with < or >.

If, by string you mean C-string, that operation can be implemented like this:
1
2
3
4
5
6
7
int my_strcmp(char const* a, char const* b) {
  // find first differing character between the C-strings a and b  
  while (*a && *a == *b)
    ++a, ++b;
  
  return *a - *b;
}

my_strcmp() behaves according to the reference here:
https://en.cppreference.com/w/cpp/string/byte/strcmp
Last edited on
Topic archived. No new replies allowed.