只是发挥各地与您的代码。它不起作用,但stringByReplacingCharactersInRange不是你的问题。
你的游戏逻辑不能像它应该那样工作。拿一支笔和一张纸,然后“手动”循环遍历你的for循环,看看这一定是错误的。
下一次,如果你盯着代码半个小时,拿一支笔。这将为您节省至少4个小时:-)
您的代码存在一些问题。假设Kartoffelkäfer
是您正在查找的单词,并且用户输入了信函f
。
for (int i = textCount-1 ; i>=0; i--) {
NSString *hiddenTextField = [[NSMutableString alloc] initWithString:hiddenText.text];
// you are creating this string in every loop from the text of a (I guess) UITextField.
// I don't know what the content of this text is but I guess it is suppossed to be `______________`
// in every loop you replace the word where you replaced the _ with the correct letter with the string from the textfield.
// Btw, you are leaking this string.
NSString *aChar=[fullTextField substringWithRange:NSMakeRange(i/3,1)];
// Kartoffelkäfer has 14 chars so i is 13. And 13/3 is 4. And the character at index 4 is o
// In the next loop i is 12. And 12/3 is 4, too.
// next three loops will give you index 3. Then you get three times index 2, and so one.
// you never reach the letter f, anyway.
if ([aChar isEqualToString:@" "]) {
theRiddle= [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@" "];
}else if ([aChar isEqualToString:character]) {
theRiddle =[hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:aChar];
}else{
theRiddle = [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@"_"];
// You should not replace a unmatched character with a _ . Because already matched letters would be overwritten.
}
hiddenTextField = theRiddle;
}
我认为hiddenText.text的内容是@ “_ __ _ __ ” 和fullText.text的内容是@“ Kartoffelkäfer”。所以hiddentext和fullText的长度是一样的。
我不得不改变得到这个工作:
NSString *theRiddle;
NSString *hiddenTextField = [[[NSMutableString alloc] initWithString:hiddenText.text] autorelease];
for (int i = textCount-1 ; i>=0; i--) {
NSString *aChar=[fullTextField substringWithRange:NSMakeRange(i,1)];
if ([aChar isEqualToString:@" "]) {
theRiddle= [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@" "];
}else if ([aChar isEqualToString:character]) {
theRiddle =[hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:aChar];
}
else {
theRiddle = hiddenTextField;
}
hiddenTextField = theRiddle;
}
hiddenText.text=theRiddle;
从优秀码远的地方,但我试图改变你的代码尽可能少。
伟大的我会尝试这个尽快,但只是需要告诉的东西,直到我试过你的代码..我已经做了3分的每一个_有空间环绕它,所以隐藏的文本和全文永远不会是同样..它是它的3倍..这一切,但我会尝试你的代码与我的条件为它的一个小镊子,除非你有一个更好的想法,在3螃蟹鸿沟..感谢任何方式为您的真正有价值的帮助希望它的工作,但我必须睡它真的很晚:D – 2010-11-06 22:16:05
它的工作先生非常感谢你帮助我的一天 – 2010-11-07 11:26:56