-
string suffix
Please have a glance. It has to find if the first string suffix of second one.
e.g. 1st world
2nd hello word
hey-you done it! it is a suffix and so on
Code:
#include <stdio.h>
int strlength(char *string)
{
int i=0;
while (string[i]) i++;
return i;
}
int issuffix(char * string1, char * string2)
{
int i,e=0, rest;
rest= strlength(string1)-strlength(string2);
if (strlength(string1) > strlength(string2))
return 0;
for (i=rest; string1[i]; i++)
for (e=0; string2[i]; e++)
{
if (string1[i] != string2[e])
return 0;
}
return 1;
}
main()
{
char stringA[1024], stringB[1024];
int n;
printf("string1: ");
scanf("%c[^\n]", stringA);
printf("string2: ");
scanf("%c[^\n]", stringB);
n=issuffix(stringA,stringB);
if (n)
printf(" \"%s\" is a suffix of %s\n",stringA, stringB);
else
printf(" \"%s\" is NOT a suffix of %s\n",stringA, stringB);
}
-
string1 and string2 are bad names. Which is the potential suffix? Why not call that one ... suffix?
I'm assuming you're "not allowed" to use strlen; otherwise, use it.
If the first string to issuffix is supposed to be the potential suffix (as implied by main), then you seem to be mixing them up in calculating rest. It should be length of string2 minus length of string1.
And there's no reason to computer their lengths again after you've calculated rest. Just check if rest is negative.
And you only need a single loop in issuffix, not a double loop.
EDIT: I forgot to mention that your scanf's should be like this:
Code:
scanf(" %[^\n]", stringA);
Note the space before the % (and the lack of the c).
-
Thanks for valuable coments. This was a test q. today. failed successfully. Can you or anyone else tell me please about the space before %. What does it do?
-
Please note that
Code:
while (string[i]) i++;
can be written as
Code:
while (string[i++]);
I believe the strlen() is done this way as well. As far as the space before the expression " %[^\n]", does your string you are passing in contain a space at the beginning followed by the carriage return? When using scanf() , you really must know how your data is presented to that function for proper parsing.