代码之家  ›  专栏  ›  技术社区  ›  Vladimir Keleshev

C:计算字符串的一部分

  •  4
  • Vladimir Keleshev  · 技术社区  · 15 年前

    我找不到表达式来计算字符串的一部分。

    我想得到这样的东西:

    if (string[4:8]=='abc') {...}
    

    我开始这样写:

    if (string[4]=='a' && string[5]=='b' && string[6]=='c') {...}
    

    但是如果我需要计算字符串的很大一部分

    if (string[10:40] == another_string) {...}
    

    然后它会写太多的表达式。有现成的解决方案吗?

    3 回复  |  直到 15 年前
        1
  •  6
  •   David Thornley    15 年前

    你总是可以用 strncmp() 如此 string[4:8] == "abc" (当然,这不是c语法)可能变成 strncmp(string + 4, "abc", 5) == 0 .

        2
  •  2
  •   puffpio    15 年前

    您需要的标准C库函数是 strncmp . strcmp 比较两个C字符串,和通常的模式一样,“N”版本处理有限长度的数据项。

    if(0==strncmp(string1+4, "abc", 4))
        /* this bit will execute if string1 
           ends with "abc" (incluing the implied null)
           after the first four chars */
    
        3
  •  0
  •   IVlad    15 年前

    这个 strncmp 其他人发布的解决方案可能是最好的。如果您不想使用strncmp,或者只是想知道如何实现自己的功能,可以编写如下内容:

    int ok = 1;
    for ( int i = start; i <= stop; ++i )
        if ( string[i] != searchedStr[i - start] )
        {
            ok = 0;
            break;
        }
    
    if ( ok ) { } // found it
    else      { } // didn't find it