将字符串与另一个字符串的字符进行比较?

时间:2014-05-27 23:35:07

标签: objective-c nsstring

到目前为止,这是我的计划。我的目的是让if语句将字符串letterGuessed中的字母与字符串userInputPhraseString中的字符进行比较。这就是我所拥有的。在xCode中编码时,我得到一个“预期'['”错误。我不明白为什么。

NSString *letterGuessed = userInputGuessedLetter.text;
NSString *userInputPhraseString = userInputPhraseString.text;

int loopCounter = 0;
int stringLength = userInputPhraseString.length;

while (loopCounter < stringLength){
    if (guessedLetter isEqualToString:[userInputPhraseString characterAtIndex:loopIndexTwo])
        {
        //if statement true
        }
    loopCounter++;
}

2 个答案:

答案 0 :(得分:1)

您在此行上缺少方括号:

    if (guessedLetter isEqualToString:[userInputPhraseString characterAtIndex:loopIndexTwo])

应该是:

    if ([guessedLetter isEqualToString:[userInputPhraseString characterAtIndex:loopIndexTwo]])
但是,

修改无法解决您的问题,因为characterAtIndex:会返回unichar,而不是NSString

答案 1 :(得分:0)

目前还不清楚你要做什么..但我认为这封信有一个字符......而且userInputPhraseString有很多字符。所以你想知道letterGuessed是否在userInputPhraseString中是否正确?

这是一个没有循环的解决方案..我用固定值替换输入进行测试并测试代码..它有效。

NSString *letterGuessed = @"A"; //Change to your inputs
NSString *userInputPhraseString = @"BBBA"; //Since it has A it will be true in the test

NSCharacterSet *cset = [NSCharacterSet characterSetWithCharactersInString:letterGuessed];
NSRange range = [userInputPhraseString rangeOfCharacterFromSet:cset];
if (range.location != NSNotFound) { //Does letterGuessed is in UserInputPhraseString?
    NSLog(@"YES"); //userInput Does contain A...
} else {
    NSLog(@"NO");
}

关于你的代码......我修复了一些错误,首先你试图获得角色的UniChar(整数)值,并希望将它与作为Object的NSString进行比较。还修复了一些与语法有关的问题,并使用了正确的方法来返回一系列字符。再一次做你想要完成的事情,上面的例子是我所知道的最好的方法,但为了学习,这里修复了你的代码。

NSString *letterGuessed = @"A"; //Change to your inputs
NSString *userInputPhraseString = @"BBBA"; //Since it has A it will be true in the test

NSInteger loopCounter = 0; //Use NSInteger instead of int. 
NSInteger stringLength = userInputPhraseString.length;
BOOL foundChar = NO; //Just for the sake of returning NOT FOUND in NSLOG

while (loopCounter < stringLength){
    //Here we will get a letter for each iteration.
    NSString *scannedLetter = [userInputPhraseString substringWithRange:NSMakeRange(loopCounter, 1)]; // Removed loopCounterTwo
    if ([scannedLetter isEqualToString:letterGuessed])
    {
        NSLog(@"FOUND CHARACTER");
        foundChar = YES;

    }
    loopCounter++;
}

if (!foundChar) NSLog(@"NOT FOUND");

NSRange保持位置,长度..所以我们在每次迭代时移动到一个新位置然后得到1个字符。

此外,如果您想要这种方法,我强烈建议使用for循环。

相关问题