String truncation with Chinese characters appears half a "Chinese character" solution-C language source code

Source: Internet
Author: User

Chinese characters are encoded in double-byte, and for Chinese characters and single-byte characters, if the target intercept string contains only an odd number of single-byte characters, then the problem of half Chinese characters will appear. As shown below:

(1) No. 2nd South Guo Lu, Tianshui Qinzhou District (ICBC Qi Li dun sub-branches?) -- contains numeric characters, single byte .

(2) No. 3rd, building 20th, Jinfu Garden, Qilihe District City, Gold Harbour City?-- contains numeric characters, single-byte.

(3) Gansu Silver Xin Spring Catering Service Co., Ltd. (party committee---------- English format half brackets included.

  The above is the result of capturing the first four bits of the string, where "? "For half a Chinese character coding display. To solve these problems, you can use the method of intercepting the last illegal character and replacing it with a valid character. The instance code is as follows:

#include <stdio.h>int Chkhalfchinese (char *buf,int len) {        int i = 0;    int cnt = 0;    int idx;    for (i=0;i<len;i++)     {           int value = buf[i]&0xff;        if (value>160)            {           cnt++;              idx=i;         }     }    if (cnt%2)     {        Buf[idx] = ';        return (1);     }    else        {        return (0)}      } int main (void) {  char str[44] = "Tianshui Qinzhou zone South Guo Lu 2 ah (ICBC Li Qi Dun sub-branches home";    if (Chkhalfchinese (str,40) ==1)  {    printf ("true\n");  }  else  {    printf ("false\n");  }  printf ("%s\n", &str);  return 0;}

  


The program code is tested in the Linux environment and the results are as follows:

String truncation with Chinese characters appears half a "Chinese character" solution-C language source code

Related Article

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.