Truncate narrow string converted from Unicode string

Source: Internet
Author: User

Now we have one Unicode string, and we want to convert it to be narrow string which means multi byte string and truncate it to desired length.
There is one key point: in Unicode string, two bytes represent one charactor; after it is converted into multi byte string, two or one bytes can represent one charactor. wether the charactor can be displayed correctly without being '? ', Firstly the correct code page for non-Unicode program shocould be set; second we need to make sure the Unicode byte after truncating must be in a pair. below function is for such purpose use.

Void truncatefilename (utxstring8 & narrstrfilename, unsigned ndestinum)
{
// No need to truncate file name.
If (narrstrfilename. Length () <ndestinum)
Return;

// Truncate file name to be desired length.
Narrstrfilename = narrstrfilename. substr (narrstrfilename. Length ()-ndestinum, ndestinum );

// Truncate one more byte if finding the number of Unicode char byte is odd, which means
// Half of the original UNICODE character has been truncated so we need to remove the other
// Half.
//
Int ncharnum = narrstrfilename. Length ();
Int nunicodecharnum = 0;
For (INT I = 0; I! = Ncharnum; ++ I)
{
Char cchar = narrstrfilename. at (I );

// Half of an Unicode Character occupies one byte and it can always be translated to be
// A negative integer.
// Once reach to a ASCII char, stop the counting because left Unicode chars are definitely
// Pair by pair.
If (cchar <0)
++ Nunicodecharnum;
Else
Break;
}

If (nunicodecharnum % 2 = 1) // odd number.
Narrstrfilename = narrstrfilename. substr (1, nCharNum-1 );

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.