我正在使用AVSpeechSynthesizer读取一个字符串,但如果字符串包含任何特殊字符,如表情符号微笑,它会给出一个错误。
如何清理字符串中的特殊字符,但保留对日语和中文的支持?
发布于 2013-11-20 02:11:16
将NSString方法stringByTrimmingCharactersInSet与NSCharacterSet字母数字的反转集一起使用,这将过滤出表情符号
因此,如果包含表情符号和中文字符的字符串被称为“textWithEmoji”,那么
NSString *textToSpeak = [textWithEmoji stringByTrimmingCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];“textToSpeak”将是相同的文本,但没有表情符号和其他非字母数字字符
发布于 2014-05-06 09:46:49
尝试使用带有空格的this.Replace表情字符串。
注意:如果你需要突出显示像表情这样的文本,不要只删除表情字符串,因为- (void)speechSynthesizer:willSpeakRangeOfSpeechString:utterance: UITextView方法会得到错误的范围。
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;}
https://stackoverflow.com/questions/20076833
复制相似问题