简体   繁体   中英

how to compare two 2 d string without using strcmp

I have data file in which some data is kept. example: welcome user HII if while
I have made 2D character array to store all the keywords in c. now I want two know if the data file contain the keyword or not.

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]);

here the k[i] represents the 2D character array where all the keywords in c are stored and t[i] represents the 2D character array where all the words of file are stored. I want to compare these 2D arrays without using strcmp.

To compare two strings without using standard C functions you can use a loop like that

#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;
}

The program output is

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

Or you can write a separate function. For example

#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;
}

the program output is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM