【问题标题】:C strcmp to compare string with first x characters of arrayC strcmp将字符串与数组的前x个字符进行比较
【发布时间】:2014-11-06 18:27:56
【问题描述】:

我想比较两个字符串,但我要查找的单词在 40 个字符的数组中。所以我想要的是将单词与数组的前 40 个字符进行比较。

我该怎么做?

所以:

words[1] = "apple"
words2[1] = a
words2[2] = p
words2[3] = p
words2[4] = l 
words2[5] = e

代码

int j;
for(j = 0; j < i; j++)
{
    printf("%s\n", words[j]);

    if (strcmp (words[j], words2[]) == 0)
    {
    // found it
    }
}

【问题讨论】:

  • @user3121023 array 确实需要空终止,只是指出这一点

标签: c arrays string strcmp


【解决方案1】:

strstr 将采用两个以空结尾的字符串,并告诉您一个是否在另一个中。此示例在 array 中查找 word

#include<stdio.h>
#include<stdlib.h>

int main() {
    char array[] = {"an array of several words"};
    char word[] = { " of "};
    char *pchar = NULL;

    pchar = strstr ( array, word);
    if ( pchar) {
        printf ( "found %s in %s\n", word, array);
    }

    return 0;
}

【讨论】:

  • 很好,但它与问题有什么关系?在示例中,数组似乎没有以空值结尾,我将问题理解为 is string 等于数组的开头,而您回答 is a string contains in another string :-( 。此外,您在字符串周围使用了毫无意义且相当混乱的括号。无法理解您是如何获得 +1 ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 2011-03-20
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多