Converting byte position to character position

Chris Angelico <[email protected]>
Newsgroups gmane.comp.lang.pike.user
Message-ID <CAPTjJmp6V-voWFHCV+nMP6PPoF3yYmWY=UCJXwVPkYmBC5e_cA@mail.gmail.com>
The context to this question involves GTK2.Pango.Layout's
xy_to_index() method, which returns the byte index into a (presumably)
UTF-8 encoded version of the string. But it's really a string
manipulation question, independent of GTK.

What's the easiest/simplest/cleanest/best way to convert a byte
position into a character position? My current solution looks like
this:

string txt = "Sermon \u201cLife Changed by an Encounter with Jesus\u201d (IBO)";
int pos = 10;
int charpos = sizeof(utf8_to_string(string_to_utf8(txt)[..pos-1]));
// and charpos ends up 8, which is correct.

And it works, but ow! what a mess. I could alternatively go through
the string manually, counting up by byte range (<127 = add one, <0x800
= add two, etc), but I suspect that'll work out even messier. Is there
a cleaner way to do this?

ChrisA
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.