0
I made a function search for a character in a string. The input parameters are the string and the character. The function returns 1 (one) if the character exists in the string or zero otherwise. The user must enter, through the keyboard, the string and the character.
Follow the code below, made normal and using pointers, but regardless of which character digit is falling into Else?: printf(" n n Character not found. n");
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int localiza(char string[], char letra){//funcao verifica se a palavra contem a letra
int i;
for( i=0; string[i] != '\ 0';i++){
if(string[i] == 'letra'){
printf("\n\n O caracter foi encontrado: %s \n",string[i]);
return 1;
}else{
printf("\n\n O caracter nao foi encontrado.\n");
return 0;
}
}
}
main(){
char str[20];
char ctr;
int k,i,num;
printf("\n Informe a string: ");
gets (str);
printf("\n Informe o caractere que deseja procurar: ");
scanf("%c",&ctr);
localiza(str,ctr);//chama a funcao de verificar se a letra esta na palavra
printf("\n\n");
system("pause");
}
Another code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int localiza(char *s1, char *s2){//funcao verifica se a palavra contem a letra
int i;
if(strstr(s1, s2)){
printf("\n\n O caracter foi encontrado! \n");
return 1;
}else{
printf("\n\n O caracter nao foi encontrado!\n");
return 0;
}
}
main(){
char str[20];
char ctr[1];
int k,i,num;
printf("\n Informe a string: ");
gets (str);
printf("\n Informe o caractere que deseja procurar: ");
gets(ctr);
//scanf("%c",&ctr);
char *ptr_str=str;
char *ptr_ctr=ctr;
localiza(str,ctr);//chama a funcao de verificar se a letra esta na palavra
printf("\n\n");
system("pause");
}
bigown is not duplicated, that other one does not answer my question.. My problem is not in comparing strings. I compare a character with a string and never find the same value.
– ADR
Where do you compare?
– Maniero
In the first code: if(string[i] == 'letter'){ printf(" n The character was found: %s n",string[i]); Return 1; }Else{ printf(" n n The character was not found. n"); turn 0; } In the second code: if(strstr(S1, s2)){ printf(" n The character was found! n"); Return 1; }Else{ printf(" n n The character was not found! n"); Return 0; }
– ADR
There you are comparing strings, wrong way, but that’s exactly what’s in that question.
– Maniero
hum.. I still don’t understand, thank you
– ADR