R
R
re3r02021-07-03 20:58:35
C++ / C#
re3r0, 2021-07-03 20:58:35

How to improve string comparison code?

#include <stdio.h>

int compare_word(char *word_one, char *word_two){
  for (int i = 0; (*(word_one + i) != '\0') || (*(word_two + i) != '\0'); ++i)
    if (*(word_one + i) != *(word_two + i))
      return 0;

  return 1;
}


int main(){

  char word_one[] = "helloworld";
  char word_two[] = "helloworld !";

  if (compare_word(&word_one[0], &word_two[0]))
    printf("%s\n", "all is ok !");
  else
    printf("%s\n", "all is not ok !");
  return 0;
}


Or tell me that there is nowhere to improve further and my soul will calm down.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
CityCat4, 2021-07-03
@CityCat4

Well, look at the source of strcmp . Because if the first line for example is "I love toster and spent here many hours" and the second is "I love toster" - then you grab SIGSEGV, because the first line is still running, and the second has already ended (and to check the condition for terminating the loop both conditions must be calculated

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question