【发布时间】:2021-05-16 10:38:48
【问题描述】:
我正在使用一个旧的objectiveC 例程(我们称之为oldObjectiveCFunction),它解析一个字符串来分析每个字符。分析完字符后,它将字符串分成字符串,并将它们返回到一个名为 *functions 的数组中。这是一个关于旧函数如何进行字符串解析的超级简化示例:
NSMutableArray *functions = [NSMutableArray new];
NSMutableArray *components = [NSMutableArray new];
NSMutableString *sb = [NSMutableString new];
char c;
int sourceLen = source.length;
int index = 0;
while (index < sourceLen) {
c = [source characterAtIndex:index];
//here do some random work analyzing the char
[sb appendString:[NSString stringWithFormat:@"%c",c]];
if (some condition){
[components addObject:(NSString *)sb];
sb = [NSMutableString new];
[functions addObject:[components copy]];
}
}
稍后,我将使用 Swift 代码获取每个 *functions 字符串:
let functions = oldObjectiveCFunction(string) as? [[String]]
functions?.forEach({ (function) in
var functionCopy = function.map { $0 }
for index in 0..<functionCopy.count {
let string = functionCopy[index]
}
}
问题在于,它与普通字符串完美配合,但如果字符串包含俄语名称,如下所示:
РАЦИОН
输出,我的let string 变量的内容,是这样的:
\u{10}&\u{18}\u{1e}\u{1d}
我怎样才能得到相同的俄语字符串而不是那个?
我试过这样做:
let string2 = String(describing: string?.cString(using: String.Encoding.utf8))
但它会返回更奇怪的结果:
"Optional([32, 16, 38, 24, 30, 29, 0])"
【问题讨论】:
-
如果您尝试在 Objective-C 而不是 Swift 中使用字符串,这些字符串看起来还可以吗?
-
我猜
%c的意思是8位无符号字符(无符号字符);尝试%C说明符16 位UTF-16 代码单元(unichar)。 -
@JosefZ 看起来您对
%c与%C的看法是正确的。您应该将其发布为答案,因为 8 位无符号字符不可能包含西里尔字符。 -
在第 4 行声明
unichar c;而不是char c;(对不起,我不会说 swift 或 Objective-C 所以我我不确定语法是否正确)。
标签: ios objective-c swift string utf-8