1

我正在使用 AVSpeechSynthesizer 读取字符串,但如果字符串包含任何特殊字符(如表情符号微笑),则会出错。

如何清除特殊字符的字符串但保留对日文,中文的支持?

4

2 回答 2

1

使用 NSString 方法 stringByTrimmingCharactersInSet 与 NSCharacterSet 字母数字的倒置集,这将过滤掉表情符号

因此,如果您的包含表情符号和中文字符的字符串称为“textWithEmoji”,那么

NSString *textToSpeak = [textWithEmoji stringByTrimmingCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];

'textToSpeak' 将是相同的文本,但没有表情符号,以及其他没有字母数字字符

于 2013-11-19T18:11:15.657 回答
1

试试这个。用空格替换表情符号字符串。

注意:如果你需要像 UITextView 这样高亮文本,不要只删除 emoji 字符串,因为 - (void)speechSynthesizer:willSpeakRangeOfSpeechString:utterance: 委托方法会得到错误的范围。

NSMutableString *string = [NSMutableString string];
NSString *text = @"Text with emoji.";    

[text enumerateSubstringsInRange:NSMakeRange(0, text.length)
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                              if ([substring isEmojiString]) {
                                  // If you need highlight text,replace the emoji with white space
                                  for (int i=0; i<substring.length; i++) {
                                      [string appendString:@" "];
                                  }
                              } else {
                                  [string appendString:substring];
                              }
                          }];

NSString 类别

- (BOOL)isEmojiString {

BOOL returnValue = NO;
const unichar hs = [self characterAtIndex:0];
// surrogate pair
if (0xd800 <= hs && hs <= 0xdbff) {
    if (self.length > 1) {
        const unichar ls = [self characterAtIndex:1];
        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
        if (0x1d000 <= uc && uc <= 0x1f77f) {
            returnValue = YES;
        }
    }
} else if (self.length > 1) {
    const unichar ls = [self characterAtIndex:1];
    if (ls == 0x20e3) {
        returnValue = YES;
    }

} else {
    // non surrogate
    if (0x2100 <= hs && hs <= 0x27ff) {
        returnValue = YES;
    } else if (0x2B05 <= hs && hs <= 0x2b07) {
        returnValue = YES;
    } else if (0x2934 <= hs && hs <= 0x2935) {
        returnValue = YES;
    } else if (0x3297 <= hs && hs <= 0x3299) {
        returnValue = YES;
    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
        returnValue = YES;
    }
}

return returnValue;

}

于 2014-05-06T01:46:49.453 回答