User Tools

Site Tools


Table of Contents

,

Reverce UTF8 sequense

C++

revu8.cpp
/*
 * Copyright Oleg Borodin  <borodin@unix7.org>
 */
 
#include <iostream>
#include <cstring>
#include <codecvt>
 
using namespace std;
 
wstring_convert<codecvt_utf8<wchar_t>> converter;
 
string& rev_utf8_str(string str) {
    auto wstr = converter.from_bytes(str);
    string buf;
    for (auto i = wstr.size(); i > 0; i-- ) {
        auto str = converter.to_bytes(wstr[i - 1]);
        buf += str;
    }
    return ref(buf);
}
 
int main(int argc, char **argv) {
    string str = "йцукенг";
    auto res = rev_utf8_str(str);
    cout << res << endl;
    return 0;
}
//EOF

Golang

revu8.go
/*
 * Copyright Oleg Borodin  <borodin@unix7.org>
 */
 
package main
 
import (
    "fmt"
    "unicode/utf8"
)
 
/*
 * Without validation
 */
 
func revUTF8String(value string) string {
 
    sourse  := []byte(value)
    runes   := make([]rune, 0)
    result  := make([]byte, 0)
 
    for len(sourse) > 0 {
        r, size := utf8.DecodeRune(sourse)
        sourse = sourse[size:]
        runes = append(runes, r)
    }
    for _, r := range runes {
        runeLen := utf8.RuneLen(r)
        buffer  := make([]byte, runeLen)
        _ = utf8.EncodeRune(buffer, r)
        result = append(buffer, result...)
    }
    return string(result)
}
 
func main() {
    fmt.Println(revUTF8String("йцукенг"))
}