unichar和NSString - 这些可以互换吗? [英] unichar and NSString - how interchangeable are these?
问题描述
有一个 NSString
方法 -characterAtIndex:
返回一个unichar。
There is an NSString
method -characterAtIndex:
which returns an unichar.
- (unichar)characterAtIndex:(NSUInteger)index
我想知道这个unichar,显然不是 NSString
,可以转换为 NSString
或者用于 NSString
用于比较目的?
I wonder if this unichar, which obviously is not an NSString
, can be converted into an NSString
or feeded to an NSString
for comparing purposes?
并且: NSString
内部只包含一系列unichar项目?
And: Does an NSString
internally just consist of an array of unichar items?
推荐答案
您有两种选择:第一个是向NSString添加stringWithUnichar方法的类别:
You have two options: the first is a category adding a stringWithUnichar method to NSString:
@interface NSString (MNNSStringWithUnichar)
+ (NSString *) stringWithUnichar: (unichar) value;
@end
@implementation NSString (MNNSStringWithUnichar)
+ (NSString *) stringWithUnichar:(unichar) value {
NSString *str = [NSString stringWithFormat: @"%C", value];
return str;
}
@end
然后用
NSString *otherString = @"TestString";
NSString *str = [NSString stringWithUnichar:[otherString characterAtIndex:1]];
或者你可以直接这样:
NSString *str = [NSString stringWithFormat:@"%C",[otherString characterAtIndex:1]];
如果要重复使用,或者只需要执行一次,请选择类别,使用stringWithFormat示例!!
Choose the category if you want to use it repeatedly, or if you only have to do it once, use the stringWithFormat example!!
不确定NSString的内部结构,但我猜它可能包含了一个
Not to sure about the internals of NSString, but I'd guess it is probably wrapping a
unichar *
或一系列unichars (比如C char *)
or an array of unichars (like a C char *)
unichar只是一个16位的值,用于存储一个字符。与只有8位的无符号字符不同,它可以保存超过0-255,因此它也可以保存unicode字符,即16位。 NSString是一个(集群)类[es],包含一个unichars数组
A unichar is simply a 16bit value that is used to store a character. Unlike an unsigned char which is only 8 bits, it can hold more than 0-255, so it can hold unicode characters as well, which are 16bits. A NSString is a (cluster of) class[es] that contains an array of unichars
EDIT
以下是一些关于人们认为NSString是什么的文章:
Here are a few articles about what people think an NSString is:
http://cocoawithlove.com/2008/08/string-philosophies-char-arrays.html
希望有所帮助!
这篇关于unichar和NSString - 这些可以互换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!