truncate narrow string converted from unicode string

來源:互聯網
上載者: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 should 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);

 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.