How to truncate utf8 text

For example you have got some data from server in utf8 format and store it in some char(byte) array . Every symbol in text could be presented with different amount of bytes, here is example how to cut (restrict) it to desired lenght. Note: allocated clippedStr should be freed after usage...
#include <utils_i18n.h>

char* utf8_text_truncate(const char *utf8_text, int length)
{
    i18n_uchar uStr[strlen(utf8_text) + 1];

    char *clippedStr = NULL;

    clippedStr  = (char*) malloc( (strlen(utf8_text)+1)*sizeof(char) );

    i18n_ustring_copy_ua(uStr, utf8_text);
    if(i18n_ustring_get_length(uStr)>length)
    {
       uStr[length] = 0;
       i18n_ustring_copy_au(clippedStr, uStr);
    }
    else
    {
       strcpy(clippedStr, utf8_text);
    }

    return clippedStr;
}

Responses

0 Replies