【问题标题】:Difference of stricmp and _stricmp in Visual Studio?Visual Studio中stricmp和_stricmp的区别?
【发布时间】:2012-09-06 23:21:31
【问题描述】:

我可能会问一个愚蠢的问题,但我真的无法通过 google 找到答案,而且我仍然是使用 MSVS 的初学者。

我最近需要使用函数来比较两个字符串。我不明白的是 stricmp 和 _stricmp 的区别。它们都可用于比较字符串并返回相同的结果。我去检查他们:

char string1[] = "The quick brown dog jumps over the lazy fox";
char string2[] = "The QUICK brown dog jumps over the lazy fox";

void main( void )
{
   char tmp[20];
   int result;
   /* Case sensitive */
   printf( "Compare strings:\n\t%s\n\t%s\n\n", string1, string2 );
   result = stricmp( string1, string2 );
   if( result > 0 )
      strcpy( tmp, "greater than" );
   else if( result < 0 )
      strcpy( tmp, "less than" );
   else
      strcpy( tmp, "equal to" );
   printf( "\tstricmp:   String 1 is %s string 2\n", tmp );
   /* Case insensitive */
   result = _stricmp( string1, string2 );
   if( result > 0 )
      strcpy( tmp, "greater than" );
   else if( result < 0 )
      strcpy( tmp, "less than" );
   else
      strcpy( tmp, "equal to" );
   printf( "\t_stricmp:  String 1 is %s string 2\n", tmp );
}

结果表明它们是相同的:

Compare strings:
    The quick brown dog jumps over the lazy fox
    The QUICK brown dog jumps over the lazy fox

    stricmp:   String 1 is equal to string 2
    _stricmp:  String 1 is equal to string 2

我想知道为什么...

【问题讨论】:

    标签: c++ case-sensitive string-comparison case-insensitive


    【解决方案1】:

    对于许多库函数,包括所有&lt;string.h&gt; 函数,下划线前缀版本是/是微软的想法。我不记得具体是什么了。

    没有下划线的版本是高度可移植的。如果代码将由另一个编译器处理,则必须以某种方式处理使用 _stricmp()_strcpy() 等的代码——编辑、#defined 等。

    【讨论】:

    • 然而,stricmp_stricmp 都不是标准 C 和 C++ 的一部分;从技术上讲,stricmp 不是&lt;string.h&gt; 功能之一。但这是一个非常常见的扩展。
    • @PeteBecker:是的,虽然有些图书馆有strcmpi()strcasecmp()
    • 感谢您的回答 wallyk。我认为使用'stricmp'(不是_stricmp)使代码可移植可能非常有帮助。因为我正在寻找函数strcasecmp()strncasecmp() 的替换。到目前为止,我的理解是可以使用(_)stricmp(_)strnicmp 作为替代品。
    【解决方案2】:

    stricmp 是 POSIX 函数,而不是标准 C90 函数。为避免名称冲突,Microsoft 弃用了不符合要求的名称 (stricmp),并建议改用 _stricmp。功能上没有区别(stricmp 只是_stricmp 的别名。)

    【讨论】:

    • 前导下划线表示它是供应商特定符号,不应与任何用户符号或未来标准冲突。
    • 感谢 StarPilot。我将在我的项目中使用 _stricmp。其他功能也一样吗?
    • stricmp 不是 POSIX 函数,它是 Win32 函数。 POSIX 定义了strcasecmp
    • Microsoft 在其文档中声明它们是 POSIX 函数。例如,请参阅:msdn.microsoft.com/en-us/library/ms235365(v=vs.80).aspx
    • @StarPilot 那么微软的文档是错误的。我已经搜索了 POSIX.1-2008 并且其中甚至没有提到stricmp。正如 Jonathan Wakely 所说,POSIX 定义了strcasecmp
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多