//finding a string in strings array
#include<stdio.h>
int strStr(char *str1, char *str2);
int main()
{
char str1[100],str2[10];
printf("Enter few strings:\n");
gets(str1);
printf("Enter the string to search:\n");
gets(str2);
int result;
result=strStr(str1,str2);
if(result==0)
printf("Equals\n");
else
printf("NOT Equals\n");
//return 0;
}
int strStr(char *str1, char *str2)
{
while(*str1==*str2)
{
if(*str1=='\0' || *str2=='\0')
break;
str1++;
str2++;
}
if(*str1=='\0' && *str2=='\0')
return 0;
else
return -1;
}
/*
OUTPUT:
-bash-3.2$ gcc strCmp.c
/tmp/ccyAmuWc.o: In function `main':
strCmp.c:(.text+0x27): warning: the `gets' function is dangerous and should not be used.
-bash-3.2$ ./a.out
Enter few strings:
india
Enter the string to search:
india
Equals
-bash-3.2$ ./a.out
Enter few strings:
india
Enter the string to search:
in
NOT Equals
-bash-3.2$ ./a.out
Enter few strings:
in
Enter the string to search:
india
NOT Equals
-bash-3.2$ india
-bash: india: command not found
-bash-3.2$ ./a.out
Enter few strings:
India
Enter the string to search:
india
NOT Equals
-bash-3.2$
*/
//Alternatestrcmp: string compare -1,0,1
#include<stdio.h>
int
strcompare(char *str1, char *str2);
int
main()
{
char
str1[20];
char
str2[20];
printf("Enter
String1:\n");
gets(str1);
printf("Enter
String1:\n");
gets(str2);
int
r;
r=strcompare(str1,str2);
if(r==0)printf("Equal\n");
else
if(r>0)printf("Not Equal:%s comes after %s\n",str1,str2);
else
printf("Not Equal:%s comes after %s\n",str2,str1);
return
0;
}
int
strcompare(char *str1, char *str2)
{
while(((*str1-*str2)==0)
&& ( (*str1!='\0')|| (*str2!='\0')))
{
str1++;
str2++;
}
printf("*str1=%d,*str2=%d\n",*str1,*str2);
return(*str1-*str2);
}
/*
-bash-3.2$
./a.out
Enter
String1:
ind
Enter
String1:
ind
Equal
-bash-3.2$
./a.out
Enter
String1:
ind
Enter
String1:
india
Not
Equal:india comes after ind
-bash-3.2$
./a.out
Enter
String1:
india
Enter
String1:
ind
Not
Equal:india comes after ind
-bash-3.2$
./a.out
Enter
String1:
india
Enter
String1:
media
Not
Equal:media comes after india
-bash-3.2$
./a.out
Enter
String1:
234
Enter
String1:
123
Not
Equal:234 comes after 123
-bash-3.2$
./a.out
Enter
String1:
india
Enter
String1:
India
Not
Equal:india comes after India
*/
No comments:
Post a Comment