如何将单词分配给特定的字母?

时间:2012-10-04 16:47:17

标签: objective-c nsstring character nsdictionary morse-code

我目前正在创建一个类似于摩尔斯电码的应用程序,使用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;
}

2 个答案:

答案 0 :(得分: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中隐藏密钥和值的顺序。

答案 1 :(得分: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 :)
      }
    }
}

尝试一下:)