Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

For the "reversing Unicode text" problem the easiest C++ solution is probably to use an external library such as QtCore or ICU (Qt uses ICU internally).

Unfortunately even in UTF-16 grapheme clusters do not correspond 1:1 with Unicode code points so you wouldn't be able to just reverse a list. But Qt can split up a QString into its grapheme clusters (a quick example I had made a couple of months ago):

    static QString reverse(QString src)
    {
        auto src_nfc = src.normalized(QString::NormalizationForm_C);
        QChar *start = src_nfc.data();
        int length = src_nfc.length();

        QTextBoundaryFinder finder(QTextBoundaryFinder::Grapheme, start, length);
        finder.toStart();

        // Reverse code elements that make up a code point when that code point has
        // been expressed in more than one code element (which is even possible in
        // UCS-4!)
        while(finder.position() < src_nfc.length()) {
            int oldPos = finder.position();
            finder.toNextBoundary();
            int newPos = finder.position();

            if(newPos - oldPos > 1) {
                std::reverse(start + oldPos, start + newPos);
            }
        }

        std::reverse(start, start + length);
        return src_nfc;
    }


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: