gpt4 book ai didi

c - 如何在不使用strcmp的情况下比较两个二维字符串

转载 作者:行者123 更新时间:2023-11-30 19:26:15 25 4
gpt4 key购买 nike

我有数据文件,其中保存了一些数据。示例:欢迎用户 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 函数,您可以使用这样的循环

#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]

关于c - 如何在不使用strcmp的情况下比较两个二维字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57774127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com