21xrx.com
2025-06-21 21:49:52 Saturday
登录
文章检索 我的文章 写文章
C++如何提取字符串中的中文字符?
2023-07-04 18:57:28 深夜i     35     0
C++ 字符串 中文字符 提取

C++是一种强大的编程语言,可以用于各种类型的编程任务。其中,提取字符串中的中文字符是一项非常常见的任务。本文将介绍一些方法来实现这个任务。

一、利用string和STL库

使用C++的string和STL库非常方便,可以使用迭代器简单地处理字符串。下面是一个例子:

#include <iostream>
#include<string>
using namespace std;
int main()
{
  string s = "hello你好world";
  cout<<s<<endl;
  for (auto c : s)
  {
    if ((c & 0xC0) == 0x80)continue; // 排除非中文字符
    cout << c;
  }
  cout << endl;
  return 0;
}

二、使用正则表达式

C++11引入了正则表达式库,可以使用正则表达式来提取中文字符。下面是一个例子:

#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
  wstring wstr = L"hello你好world";
  wregex reg{ L"[\u4e00-\u9fa5]+" };
  wsmatch result;
  regex_search(wstr, result, reg);
  for (auto s : result)
  
    wcout << s << " ";
  
  wcout << endl;
  return 0;
}

三、使用ICU库

ICU是一个国际化软件开源库,提供了一些C++接口,用于处理具有语言复杂性的文本。ICU库可用于提取中文字符。下面是使用ICU库的一个例子:

#include <iostream>
#include <unicode/unistr.h>
using namespace icu;
using namespace std;
int main()
{
  StringCharacterIterator iter(u"hello你好world");
  for (; !iter.done(); iter.next())
  {
    UChar32 c = iter.current32();
    if (u_isalpha(c))
    {
      cout << char(c);
    }
  }
  cout << endl;
  return 0;
}

对于对中文字符的处理,使用C++的STL库、正则表达式和ICU库都是可行的方法,并且在处理不同类型的文本时都比较灵活。开发人员可以根据实际需求,选择最适合自己的方法来提取中文字符。

  
  

评论区