【问题标题】:how to compare two 2 d string without using strcmp如何在不使用 strcmp 的情况下比较两个二维字符串
【发布时间】:2019-09-03 14:49:58
【问题描述】:

我有一个数据文件,其中保存了一些数据。 例如:welcome user HII if while
我已经制作了二维字符数组来将所有关键字存储在 c 中。 现在我想知道数据文件是否包含关键字。

enter code here
  for(i=0;i<32;i++)
  for(j=0;j<no_of_words_in_file;j++)
      if(k[i]==t[j])
         printf("%s is keyword",t[j]);

这里的k[i]代表存储c中所有关键字的二维字符数组,t[i]代表存储file所有单词的二维字符数组。 我想在不使用 strcmp 的情况下比较这些二维数组。

【问题讨论】:

  • 您不能在 C 中将字符串与 == 进行比较。您需要隔离文件中的每个单词,然后使用 strcmp 或类似方法将其与数组中的每个关键字进行比较自己设计的功能。如果你不想使用strcmp,那么第一个工作就是编写等效函数。
  • 您在寻找 strcmp 的替代品吗?自己实现可以吗?
  • strcmp 有什么问题?这听起来像:我想在不使用打印机的情况下打印我的 word 文档

标签: c loops while-loop string-comparison c-strings


【解决方案1】:

要在不使用标准 C 函数的情况下比较两个字符串,您可以使用这样的循环

#include <stdio.h>

int main(void) 
{
    char key[]   = "while";
    char word1[] = "while";
    char word2[] = "when";

    size_t i = 0;

    while ( key[i] != '\0' && key[i] == word1[i] ) ++i;

    int equal = key[i] == word1[i];

    printf( "key == word1: = %d\n", equal );

    i = 0;

    while ( key[i] != '\0' && key[i] == word2[i] ) ++i;

    equal = key[i] == word2[i];

    printf( "key == word2: = %d\n", equal );

    return 0;
}

程序输出是

key == word1: = 1
key == word2: = 0

或者您可以编写一个单独的函数。例如

#include <stdio.h>

int equal( const char *s1, const char *s2 )
{
    while ( *s1 != '\0' && *s1 == *s2 ) 
    {
        ++s1; ++s2;
    }

    return *s1 == *s2;
}

int main(void) 
{
    enum { N = 10 };
    char key[][N] ={ "if",  "while" };
    const size_t N1 = sizeof( key ) / sizeof( *key );
    char words[][N] = { "welcome", "user", "HII", "if",  "while" };
    const size_t N2 = sizeof( words ) / sizeof( *words );

    for ( size_t i = 0; i < N2; i++ )
    {
        for ( size_t j = 0; j < N1; j++ )
        {
            if ( equal( key[j], words[i] ) )
            {
                printf( "\"%s\" == \"%s\"[%zu]\n", key[j], words[i], i );
            }               
        }
    }

    return 0;
}

程序输出是

"if" == "if"[3]
"while" == "while"[4]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多