2017-02-21 11 views
0

次のコードを使用して、文字列のデータをchar *に格納しています。ギリシャ文字でNSString to char *

NSString *hotelName = [components[2] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
hotelInfo->hotelName = malloc(sizeof(char) * hotelName.length + 1); 
strncpy(hotelInfo->hotelName, [hotelName UTF8String], hotelName.length + 1); 
NSLog(@"HOTEL NAME: %s",hotelInfo->hotelName); 

問題はギリシア文字が奇妙に印刷されていることが原因です。

hotelInfo->hotelName = (const char *)[hotelName cStringUsingEncoding:NSUnicodeStringEncoding]; 

それはまた奇妙な文字を生成します。私も、私もそれを試してみました別のエンコード(例えばNSWindowsCP1253StringEncoding -it crashes-)

を使用しようとしました。

私は何が間違っていますか?

EDIT:

if ([hotelName canBeConvertedToEncoding:NSWindowsCP1253StringEncoding]){ 
    const char *cHotelName = (const char *)[hotelName cStringUsingEncoding:NSWindowsCP1253StringEncoding]; 
    int bufSize = strlen(cHotelName) + 1; 
    if (bufSize >0){ 
     hotelInfo->hotelName = malloc(sizeof(char) * bufSize); 
     strncpy(hotelInfo->hotelName, [hotelName UTF8String], bufSize); 
     NSLog(@"HOTEL NAME: %s",hotelInfo->hotelName); 
    } 
}else{ 
    NSLog(@"String cannot be encoded! Sorry! %@",hotelName); 
    for (NSInteger charIdx=0; charIdx<hotelName.length; charIdx++){ 
     // Do something with character at index charIdx, for example: 
     char x[hotelName.length]; 
     NSLog(@"%C", [hotelName characterAtIndex:charIdx]); 
     x[charIdx] = [hotelName characterAtIndex:charIdx]; 
     NSLog(@"%s", x); 
     if (charIdx == hotelName.length - 1) 
      hotelInfo->hotelName = x; 
    } 
    NSLog(@"HOTEL NAME: %s",hotelInfo->hotelName); 
} 

しかし、まだ何も:私は次のことを試してみましたいくつかの提案をした後

+0

あなたは 'characterAtIndex'を使用してみましたか? Objective-cにはたくさんの機能が組み込まれていて、約1行のコードですべてを実行できるようになっています。 iOSアプリの笑で使われている古くなったCを見るのは変だ。 (私は間違っている、私はCが大好きではない) –

+0

あなたの問題は解決されますか? – KrishnaCA

+0

@KrishnaCA私の質問を編集しました – arniotaki

答えて

1

まず、NSStringをC文字配列(いわゆるC-String)として表すことはできません。その理由は、使用できる文字のセットが限られているからです。文字列を変換できるかどうかを確認する必要があります(canBeConvertedToEncoding:を呼び出して)。

mallocstrncpy機能を使用する場合第二に、それらはCストリングの長さではなく、NSStringの長さに依存しています。ですから、最初の呼び出し、それは長さ(strlen)のget、その後、NSStringのからC-文字列を取得し、関数にこの値を使用する必要があります。

const char *cHotelName = (const char *)[hotelName cStringUsingEncoding:NSWindowsCP1253StringEncoding]; 
int bufSize = strlen(cHotelName) + 1; 
hotelInfo->hotelName = malloc(sizeof(char) * bufSize); 
strncpy(hotelInfo->hotelName, cHotelName, bufSize); 
+0

文字の大部分では機能するようですが、ポリトニックやアポストロフィでは機能しないようです。もちろん、何もしていないよりも常に良いです。 – arniotaki

+0

その場合、(Unicodeのような)異なるエンコーディングを試すことができます。唯一の重要な点は、 'strlen'、' malloc'および 'strncpy'関数に返された' const char * 'を使って、クラッシュを防ぐことです。 –

+0

NSUTF8StringEncodingは問題を解決します。ありがとう! – arniotaki