3

I have a UTF-8 encoded char*.

Is there a standard function to calculate the number of visible characters represented by the byte array?

I'm on Red Hat (RHEL 5).

1
  • Thank you both for your comments. glib here I come!
    – Bill
    Commented Jun 16, 2010 at 13:40

2 Answers 2

0

Check the iconv library: man iconv_open. One can convert the utf-8 string into say UCS-2 or UCS-4 where characters are of the same size. iconv is also (relatively) portable and not Linux or GNU specific.

If Glib, suggested before, is available to you (beware: it is GPLed) then use it as it is a better way.

2
  • Oh. Mea culpa. Then forget the iconv stuff.
    – Dummy00001
    Commented Jun 8, 2010 at 8:56
  • This isn't a correct answer to "get the number of visible characters", because codepoints are not the same thing as visible characters. A Unicode grapheme can composed out of any number of code points.
    – strcat
    Commented Nov 9, 2012 at 18:41
0

Yes, glib.h, has g_utf8_strlen()

Check out this page for more information (including three implementations of an algo to do this)

5
  • The documentation you pointed to doesn't indicate whether it counts non-independent characters like combining characters or diacritics. Do you know whether it does?
    – Bill
    Commented Jun 7, 2010 at 21:02
  • I think the utf8 parlance for what you speak of is graphemes, without the use of that term I would not take it to mean combining characters or diacritics. Commented Jun 7, 2010 at 21:55
  • 2
    g_utf8_strlen() only counts code points within a UTF-8 string. Thus, if you had "e\u0341" (U+0341 is a combining acute accent), you'd get 2, while the string itself will display as é.
    – Thanatos
    Commented Jun 8, 2010 at 0:12
  • That whole second link seems to be a lesson in premature optimization.
    – Thanatos
    Commented Jun 8, 2010 at 0:16
  • I disagree with this latter remark. Library code is wholly different from application code: it ought to be as fast as possible or it'll be shunned from critical performance code. Furthermore, I would argue it's not premature in the sense that it's been thought and measured and is not the result of a misconception. Commented Jun 8, 2010 at 6:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.