如何在不使用strcmp的情况下比较两个二维字符串
我有一个数据文件,其中保存了一些数据。 示例:如何在不使用strcmp的情况下比较两个二维字符串,c,loops,while-loop,string-comparison,c-strings,C,Loops,While Loop,String Comparison,C Strings,我有一个数据文件,其中保存了一些数据。 示例:欢迎用户HII if while 我已经制作了2D字符数组来存储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]); 在此处输入代码 对于(i=0;i要在不使用标准C函数的
欢迎用户HII if while
我已经制作了2D字符数组来存储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]);
在此处输入代码
对于(i=0;i要在不使用标准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;
}
或者您可以编写一个单独的函数
#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;
}
在C语言中,你不能将字符串与==
进行比较。你需要分离文件中的每个单词,然后使用strcmp
或你自己设计的类似函数将其与数组中的每个关键字进行比较。如果你不想使用strcmp
,那么第一项工作就是编写等效函数。你在寻找替代方法吗ative to strcmp?可以自己实现吗?strcmp
有什么问题?听起来像:我想不使用打印机打印word文档。
#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]