Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a string array in C++ no matter of 'A' or 'a' and with å, ä ö?

How do you sort an array of strings in C++ that will make this happen in this order:

mr Anka

Mr broWn

mr Ceaser

mR donK

mr ålish

Mr Ätt

mr önD

//following not the way to get that order regardeless upper or lowercase and å, ä, ö
//in forloop... 
string handle;
point1 = array1[j].find_first_of(' ');
string forename1(array1[j].substr(0, (point1)));
string aftername1(array1[j].substr(point1 + 1));
point2 = array1[j+1].find_first_of(' ');
string forename2(array1[j+1].substr(0, (point2)));
string aftername2(array1[j+1].substr(point2 + 1));
if(aftername1 > aftername2){
    handle = array1[j];
    array1[j] = array1[j+1];
    array1[j+1] = handle;//swapping
}
if(aftername1 == aftername2){
    if(forname1 > forname2){
        handle = array1[j];
        array1[j] = array1[j+1];
        array1[j+1] = handle;   
    }
}
like image 515
Chris_45 Avatar asked Mar 22 '10 16:03

Chris_45


People also ask

How do you sort an array of strings?

To sort an array of strings in Java, we can use Arrays. sort() function.

Can we sort a string in C?

C Sort String in Ascending Order Receive any string using gets() function. Get the length of string using strlen() function of string. h library and initialize it to any variable say len. Now create a for loop that runs from 0 to one less than the string length.


1 Answers

As soon as you throw unicode characters into the mix, you have to start thinking about internationalization. Different languages have different sorting rules. For example, in Dutch, "IJ" is considered a single letter and has its own place in the alphabet. I recommend a good Unicode library for doing string lexical comparisons, namely International Components for Unicode: http://site.icu-project.org/

With that, you can simply use the ordinary std::sort with ICU's comparator.

like image 123
Will Avatar answered Oct 18 '22 00:10

Will