【问题标题】:How do I compare single multibyte character constants cross-platform?如何跨平台比较单个多字节字符常量?
【发布时间】:2022-01-19 13:37:40
【问题描述】:

当我正在编写一个跨平台应用程序时,我希望我的代码能够在两个平台上运行。

在 Windows 中,我使用此代码比较 2 个单个字符。

for( int i = 0;  i < str.size();  i++ )
    if( str.substr( i, 1 ) == std::string( "¶" ) )
        printf( "Found!\n" );

现在,在 Linux 中,找不到该字符。当我将子字符串更改为长度为2时发现。

for( int i = 0;  i < str.size();  i++ )
    if( str.substr( i, 2 ) == std::string( "¶" ) )
        printf( "Found!\n" );

如何将此字符比较代码转换为跨平台?

【问题讨论】:

  • 您使用/期望哪种编码?
  • 我不确定,我没有具体设置。但我猜 UTF-8 就足够了?
  • 确保您的代码具有适当的编码。你怎么喂str
  • 不要为 C++ 问题标记 C。
  • @EricPostpischil 好吧,最初我想将 char 与 wchar_t 进行比较。但我转换成std::strings。所以我两个都用

标签: c++ character-encoding cross-platform multibyte


【解决方案1】:

使用字符串的str.compare()size()解决:

std::string str = "Some string ¶ some text ¶ to see";
std::string char_to_compare = "¶";

for( int i = 0;  i < str.size();  i++ )
    if( str.compare( i, char_to_compare.size(), char_to_compare ) == 0 )
        printf( "Found!\n" );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多