char | string | NSString 之间的转换

char to string

方式一

    char c1 = 'd';
    string s1(1, c1);
    cout << "s1 = " << s1 << endl;

方式二

    char c2 = 'y';
    char tc[128];
    sprintf(tc, "%c", c2);
    string s2(tc);
    cout << "s2 = " << s2 << endl;

string to char

    string s3("hello");
    unsigned long size = s3.length();
    cout << "s3 length = " << size << endl;
    const char *ch = s3.c_str();
    char mych[size + 1];
    for (int i=0; i<size; i++)
    {
        mych[i] = ch[i];
        cout << ch[i] << endl;
    }
    
    mych[size] = '\0';

char to NSString

    char c3 = 'p';
    NSString *nss = [NSString stringWithFormat:@"%c", c3];
    cout << "nss with char and nss = " << [nss UTF8String] << endl;
    NSLog(@"nss = %@", nss);

char * to NSString

    const char * c6 = "veryitman";
    NSString *nss2 = [NSString stringWithUTF8String:c6];
    NSLog(@"nss3 = %@", nss2);

NSString to char *

    NSString *nss3 = @"veryitman";
    const char * c4 = [nss3 UTF8String];
    NSLog(@"c4 = %s", c4);

string to char *

    string s7 = "veryitman";
    const char *c5 = s7.c_str();
    cout << "c5 = " << c5 << endl;

string to NSString

    string s8 = "veryitman";
    NSString *nss4 = [NSString stringWithFormat:@"%s", s8.c_str()];
    NSLog(@"nss4 = %@", nss4);

NSString to string

    NSString *nss5 = @"veryitman";
    string s9([nss5 UTF8String]);
    cout << "s9 = " << s9 << endl;

 

©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页