If I understood you well, you only need to know if all the letters of a word exist in a sentence; if so, the code is quite simple:
unsigned existe(const char *palabra, const char *frase)
{
unsigned resultado = 0u;
unsigned letras = strlen(palabra);
for (const char *buscar = palabra; *buscar; ++buscar)
{
unsigned encontrada = 0;
for (const char *en = frase; *en && !encontrada; ++en)
{
encontrada = *buscar == *en ? 1 : 0;
}
resultado += encontrada;
}
return (resultado == letras) ? 1 : 0;
}
The function existe
returns 1
if all the letters of palabra
are present in frase
and 0
otherwise. To do this, it goes from letter to letter of palabra
and compares them with all the letters of frase
, for each match for the loop and adds 1 to the counter resultado
, if at the end of the function this counter is equal to the length of the received word: then all the letters are present in the sentence:
int main()
{
char pal1[3][10] = {"sol", "agua", "luz"};
char nombre[100] = {};
printf("Escribe una frase: ");
fgets(nombre, 100, stdin);
for (int i = 0; i != 3; ++i)
printf("'%s' existe en '%s'? %d\n", pal1[i], nombre, existe(pal1[i], nombre));
return 0;
}
The previous code, if you enter the phrase hello I am a programmer , shows the following output:
'sol' existe en 'hola soy un programador'? 1
'agua' existe en 'hola soy un programador'? 1
'luz' existe en 'hola soy un programador'? 0
Keep in mind that the proposed algorithm does not take into account repetition of letters, that is: "amalgama"
would count as existing in "hola soy un programador"
even though the word has four 'a'
and the phrase has only three.