[英]How do I convert NSString to an encoding other than UTF-8?
I'm working with c
in iOS Project I'm trying to convert my string to respected type in c, below code is supposed to send to core Library我正在
c
项目中使用 c 我正在尝试将我的字符串转换为 c 中的受人尊敬的类型,下面的代码应该发送到核心库
typedef uint16_t UniCharT;
static const UniCharT s_learnWord[] = {'H', 'e','l','\0'};
what i have done till now is string
is the one what I'm passing到目前为止我所做的是
string
是我正在传递的
NSString * string = @"Hel";
static const UniCharT *a = (UniCharT *)[string UTF8String];
But it is failing to convert when more than one character, If i pass one character then working fine please let me where i miss, How can i pass like s_learnWord?
但是当超过一个字符时它无法转换,如果我通过一个字符然后工作正常请让我错过我的地方,我怎样才能像
s_learnWord?
and i tried in google
and StackOverFLow
none of the duplicates or answers didn't worked for me like this Convert NSString into char array I'm already doing same way only.我在
google
和StackOverFLow
中尝试过,没有一个重复项或答案对我不起作用,就像这样Convert NSString into char array我已经在做同样的事情了。
Your question is a little ambiguous as the title says "c type char[]" but your code uses typedef uint16_t UniCharT;
你的问题有点模棱两可,因为标题是“c type char[]”,但你的代码使用
typedef uint16_t UniCharT;
which is contradictory.这是矛盾的。
For any string conversions other than UTF-8, you normally want to use the method getCString:maxLength:encoding:
.对于 UTF-8 以外的任何字符串转换,您通常需要使用
getCString:maxLength:encoding:
方法。
As you are using uint16_t
, you probably are trying to use UTF-16?当您使用
uint16_t
时,您可能正在尝试使用 UTF-16? You'll want to pass NSUTF16StringEncoding
as the encoding constant in that case.在这种情况下,您需要将
NSUTF16StringEncoding
作为编码常量传递。 (Or possibly NSUTF16BigEndianStringEncoding
/ NSUTF16LittleEndianStringEncoding
) (或者可能是
NSUTF16BigEndianStringEncoding
/ NSUTF16LittleEndianStringEncoding
)
Something like this should work:像这样的东西应该工作:
include <stdlib.h>
// ...
NSString * string = @"part";
NSUInteger stringBytes = [string maximumLengthOfBytesUsingEncoding];
stringBytes += sizeof(UniCharT); // make space for \0 termination
UniCharT* convertedString = calloc(1, stringBytes);
[string getCString:(char*)convertedString
maxLength:stringBytes
encoding:NSUTF16StringEncoding];
// now use convertedString, pass it to library etc.
free(convertedString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.