Comparing Strings

i wrote a game and here recently i noticed a flaw in targetting monsters.

if the monster is a "Black Dragon" you can target any characters up to the space

so "attack black" "attack blac" "attack bla" "attack "bl" "attack "b"

all those work cause it compares the stringsw from left to right, but what would be a good way to go about targeting as "dragon" since "Black Dragon" is the complete name.

here is what i use to call the attack method:

if(argc == 2 && sameas(argv[0],"attack"))
{
return(attack(argv[1]));
}

this is a generic attack method:

int
attack(char *target)
{
int mnum;

chrptr=&arnarr[usrnum];

if((mnum=locmon(target,chrptr->loc))!=-1)
{
printf("\nAttempting to attack the %s.\r",target);
}
else
{
printf("\nCound not locate the %s to attack.\r", target);
}
return(mnum);
}

this is how i look for a monster in a room by name:

int
locmon(char *name,long room)
{
INT i;
for(i=0 ; i < NMON ; i++)
{
if((arnmar[i].active) && /* is monster active? */
(arnmar2[i].loc==room) && /* monster is in same room? */
(sameto(name,arnmar[i].name))) /* name characters match? */
return(i); /* return the monster # */
}
return(-1); /* no matches found */
}


this is how i compare strings from left to right:

bool /* returns TRUE=short matches */
sameto( /* compare short string to long string */
const char *shorts, /* short string to compare */
const char *longs) /* long string to compare */
{
while (*shorts != '\0') {
if (tolower(*shorts) != tolower(*longs)) {
return(false);
}
shorts++;
longs++;
}
return(true);
}

this is how i compare exact string matches:

bool /* returns TRUE=same FALSE=different */
sameas( /* are strings identical? (ignores case) */
const char *stg1, /* first string to compare */
const char *stg2) /* second string to compare */
{
while (*stg1 != '\0') {
if (tolower(*stg1) != tolower(*stg2)) {
return(false);
}
stg1++;
stg2++;
}
return(*stg2 == '\0' ? true : false);
}

my sameto method compares text from left to right til it stops matching.

what i want it to do is compare the string "target" to any series of
the monster name.

so a "Black Dragon" could essentially be attacked by going "attack drag"

any help is greatly appreciated.

first off use code tags please because it makes it much easier to read. the easiest way to compare strings is with strcmp()
read: http://www.cprogramming.com/fod/strcmp.html
Last edited on
Topic archived. No new replies allowed.