我有用特殊快捷键编码的文本报告(例如,“BLU”表示“BLUE”,@"ABV“表示”以上“,等等)。
我创建了一个NSDictionary,其中键是编码的单词,值是翻译。
目前,我使用以下代码翻译字符串:
NSMutableString *decodedDesc = [@"" mutableCopy];
for (NSString *word in [self.rawDescriprion componentsSeparatedByString:@" "]) {
NSString * decodedWord;
if (word && word.length>0 && [word characterAtIndex:word.length-1] == '.') {
decodedWord = [abbreviations[[word substringToIndex:word.length-1]] stringByAppendingString:@"."];
} else
decodedWord = abbreviations[word];
if (!decodedWord)
decodedWord = word;
[decodedDesc appendString:[NSString stringWithFormat:@"%@ ",decodedWord]];
}
_decodedDescription = [decodedDesc copy];
问题是,报告中的词语并非总是用空格分隔开来。有时,代码会连接到其他特殊字符,如@"-“或”@“/,因为”BLU-ABV“这样的词不在字典键中。
如何改进这段代码,使其在翻译单词时忽略特殊字符,但在翻译后的NSString中保留它们?例如,@"BLU-ABV“将翻译为”Blue-Above“。
发布于 2014-11-09 18:30:15
我解决了。解决方案是逐个字母地枚举原始NSString。每个字母都被添加到一个单词中,直到达到一个特殊的字符。
在到达一个特殊字符时,翻译后的单词(然后是特殊字符)被转储到已翻译的报告(这是一个NSMutableString)中,并且单词变量被重置为@"“。
下面是代码:(不包括字典或原始NSString初始化)
__block NSString *word;
NSCharacterSet *specialChars = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
[_rawDescriprion enumerateSubstringsInRange:NSMakeRange(0, [_rawDescriprion length])
options:(NSStringEnumerationByComposedCharacterSequences)
usingBlock:^(NSString *letter, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if (!word)
word = @"";
//if letter is a special char
if ([letter rangeOfCharacterFromSet:specialChars].location != NSNotFound) {
//add old word to decoded string
if (word && abbreviations[word])
[decodedDesc appendString:abbreviations[word]];
else if (word)
[decodedDesc appendString:word];
//Add the punctuation character to the decoded description
[decodedDesc appendString:letter];
//Clear word variable
word = @"";
}
else { //Alpha-numeric letter
//add letter to word
word = [word stringByAppendingString:letter];
}
}];
//add the last word to the decoded string
if (word && abbreviations[word])
[decodedDesc appendString:abbreviations[word]];
else if (word)
[decodedDesc appendString:word];
_decodedDescription = [decodedDesc copy];
发布于 2014-11-09 15:01:04
这可以通过
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@" -/"];
[self.rawDescription componentsSeparatedByCharactersInSet:characterSet];
其中characterSet包含您想要分隔的字符,或者您甚至可以用字母(只有字母或字母数字)来定义CharacterSet,然后使用invertedSet
。
发布于 2014-11-09 15:07:01
使用字符集来分隔它。
NSMutableCharacterSet* cSet = [NSMutableCharacterSet punctuationCharacterSet];
// add your own custom character
[cSet addCharactersInString:@" "];
NSArray *comps = [self.rawDescriprion componentsSeparatedByString:cSet];
您可以在苹果文档查看哪个字符集更适合您的情况。
但我会说它应该是标点符号。
https://stackoverflow.com/questions/26834087
复制相似问题