0

我目前正在制作一个类似于摩尔斯电码的应用程序,通过使用isEqualToString方法来编码,比如 A = hello, B = good。

-(NSString*)checkWords :(NSString*)words{
NSString * letter;

if (([words isEqualToString:@"a"]) || ([words isEqualToString:@"A"])){
    letter = @"hello";        }
if (([words isEqualToString:@"b"]) || ([words isEqualToString:@"B"])){
    letter = @"good";        }
return letter;

}

通过单击下面的按钮将生成代码:

- (IBAction)decodeBtn:(id)sender {

outputTextField.text = @"";
NSString * inputString = outputView.text;
int wordLength = [inputString length]; //gets a count of length

int i = 0;
while (i < wordLength) {

    unichar charToCheck = [inputString characterAtIndex:i];
    if (charToCheck != 32){ // checks to make sure its not a space

        NSString* words = [NSString stringWithCharacters:&charToCheck length:1];

        NSString * letter = [self checkWords:words];

        NSString * stringToAppend = outputTextField.text;
        if (letter != @""){
            outputTextField.text = [stringToAppend stringByAppendingString:letter];
        } else {
            // new line?
        }
        letter = nil;
    }
    i++;
  }
}

我可以得到我需要的那些单词的字母表。我想知道我应该使用哪种方法将单词解码回字母表?也就是说,当用户输入“hello good”时,输出会是“A B”?

非常感谢。

如果我这样写,应用程序会崩溃:

[EncodeViewController copyWithZone:]:无法识别的选择器发送到实例

-(NSString*)checkWords :(NSString*)words{
NSString * letter;

if ([words isEqualToString:@"hello"]) letter = @"A";
if ([words isEqualToString:@"good"]) letter = @"B";

return letter;
}
4

2 回答 2

2
NSArray* words = [sentence componentsSeparatedByString:@" '];
NSMutableString* output = [NSMutableString string];
for (NSString* word in words) {
   word = [word lowercaseString];
   NSString* letter = [translationDict objectForKey:word];
   [output appendFormat:@"%@ ", letter];
}

要创建您的 translationDict,请使用:

NSDictionary* translationDict = [NSDictionary dictionaryWithObjectsAndKeys:@"apple", @"A", @"banana", @"B", @"chocho", @"C", @"dingodog", @"D", .... @"Z", nil];

然后,您可以在任一方向使用翻译循环(如果您的各个字母由空格分隔),键和值的顺序在translationDict.

于 2012-10-04T17:31:47.540 回答
0

制作你自己的方法并从某个地方调用它,内容有点像:

if ([userInput isEqualToString:@"apple banana"]) {
    NSMutableString * firstCharacters = [NSMutableString string];
    NSArray * words = [userInput componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    for (NSString * word in words) {
      if ([word length] > 0) {
        NSString * firstLetter = [word substringToIndex:1];
        [firstCharacters appendString:[firstLetter uppercaseString]];
//NSLog firstLetter and you get the result :)
      }
    }
}

试试看 :)

于 2012-10-04T17:05:49.867 回答