0

I'm making a word game and I've finally come up to one of the most important parts of my game, the compare part.

I got this label which will be invisible when it launches with the word that has to be guessed displaying in it with a random word generator. For example the word is: GARAGE

Now, for my game I have to compare the word with the input now I've already done this with the entire word with NSString but I want it to compare every letter. I want to be able to show that if the input has G as the first letter aswell, like garage. I want it to do something.

I want to know if this is possible and which methods you would use. I was thinking about making 6 strings since all my random words have 6 letters, and then break the word to 6 strings and the input aswell and then compare strings?

Hope someone has some usefull tips or example code thanks

2 Answers2

0

So, assuming your string to be guessed...

NSString *stringToGuess = @"GARAGE";

and you were checking to see if it started with "GA"

NSString *myString = @"GA";

you would check it with hasPrefix:

if ([stringToGuess hasPrefix:myString]) {
    // <stringToGuess> starts with <myString>
}

The documentation for NSString describes lots of neat methods for just about anything string related.

Jody Hagins
  • 27,943
  • 6
  • 58
  • 87
0

hasPrefix will let you tell if one string begins with another string. There's also characterAtIndex. You could use that to get one character from each string and compare it to the other.

You could write a method that would take an integer index and compare the two strings at that index:

- (BOOL) compareStringOne: (NSString *) stringOne 
  toStringTwo: (NSString *) stringTwo
  atIndex: (NSUInteger) index;
{
  if ([stringOne length] < index+1 || [stringTwo length] < index+1)
    return FALSE;
  return [stringOne characterAtIndex: index] == [stringTwo characterAtIndex: index];
}
Duncan C
  • 128,072
  • 22
  • 173
  • 272