FastKid12
FastKid12

Reputation: 89

lexicographic comparison of strings [case-insensitive]

I want to sort the text of a file in lexicographic order but I'm having trouble understand what lexicographic order really does.

Ordering strings produces another issue; the relational operators use ASCII values so

betty < Diane is false when it should be true .

Consider a sample list : betty, Diane, 123, Ana, Megan, charles, two, 12.

How would I set that in lexicographic order?

Upvotes: 0

Views: 1881

Answers (3)

ipk
ipk

Reputation: 21

Use compareToIgnoreCase Method

Upvotes: 0

Saurav Sahu
Saurav Sahu

Reputation: 13994

Approach:

  1. Use map <convert_to_lower_case(words) as string, index as integer> to put all the words in the list.
  2. After that create a sorted vector myVec using:

    for(it_type iterator = m.begin(); iterator != m.end(); iterator++) { myVec.push_back(original_list[it->second]); }

myVec is the lexicographically sorted list you are looking for. You need to implement convert_to_lower_case(word) :

for(int i = 0; str[i]; i++){
  word[i] = tolower(str[i]);
}

Other answer is good too, uses comparator to sort the vector.

Upvotes: 2

druckermanly
druckermanly

Reputation: 2741

Does this not do what you want?

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
  std::vector<std::string> v {"Diane", "123", "Ana", "Megan", "charles", "two", "12"};

  for (const auto& s : v) {
    std::cout << s << ' ';
  };
  std::cout << '\n';

  std::sort(v.begin(), v.end(), [](const std::string& a, const std::string& b) {
    for (int i = 0 ; i < std::min(a.size(), b.size()) ; i++) {
      const auto a_char = std::tolower(a[i]);
      const auto b_char = std::tolower(b[i]);
      if (a_char != b_char) {
        return a_char < b_char;
      }
    }
    return a.size() < b.size();
  });

  for (const auto& s : v) {
    std::cout << s << ' ';
  };
  std::cout << '\n';

  return 0;
}

stdout looks like this:

Diane 123 Ana Megan charles two 12 
12 123 Ana charles Diane Megan two 

Upvotes: 1

Related Questions