简体   繁体   English

如何将Objective-C字符串转换为C字符串?

[英]How to convert Objective-C string into a C string?

I need to convert an C-String into an NSString. 我需要将C-String转换为NSString。
How do I do this? 我该怎么做呢?
I know how to convert it the OTHER WAY, 我知道如何将其转换

NSString *hello = @"Hello!";
const char *buffer;
buffer = [schoolName cStringUsingEncoding: NSUTF8StringEncoding];
NSLog(@"C-String is: %s", buffer);

However, how do I do it Objective-C string (NSString) into a NULL-TERMINATED string. 但是,如何将Objective-C字符串(NSString)转换为NULL-TERMINATED字符串。

Thanks! 谢谢!

const char *buffer = [hello UTF8String]; will do what you're looking for. 会做您想要的。

Now to answer the new (and very different) question: 现在回答新的(并且非常不同的)问题:

If you have, for example, const char *cstring = "hello world"; 例如,如果您有const char *cstring = "hello world"; you can create an NSString * with it through: NSString *nsstring = [NSString stringWithFormat:@"%s", cstring]; 您可以通过以下方式创建一个NSString *NSString *nsstring = [NSString stringWithFormat:@"%s", cstring];

There are, of course, other ways to accomplish the same thing. 当然,还有其他方法可以完成同一件事。

NSString* str = [NSString stringWithUTF8String:(const char *)]

or 要么

NSString* str = [NSString stringWithCString:(const char *) encoding:(NSStringEncoding)]

or 要么

NSString* str = [NSString stringWithCharacters:(const unichar *) length:(NSUInteger)]

Try something like this: 尝试这样的事情:

- (wchar_t*)getWideString
{
    const char* temp = [schoolName cStringUsingEncoding:NSUTF8StringEncoding];
    int buflen = strlen(temp)+1; //including NULL terminating char
    wchar_t* buffer = malloc(buflen * sizeof(wchar_t));
    mbstowcs(buffer, temp, buflen);
    return buffer;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM