2014-01-29 50 views
1

我有NSString的,如:的NSString燒焦我的[16]

NSString *str = @"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45"; 

我怎樣才能將其轉換爲字符數組,如下圖所示:

char keyPtr[16] = {225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45} 

誰能幫助!

感謝

+0

'componentsSeperatedByString'讓每一個「串號」,然後把每一個流入焦炭。那是你在哪裏阻塞? – Larme

回答

3
NSString *input = @"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45"; 
char output[16]; 

NSArray *elements = [input componentsSeparatedByString:@","]; 
NSAssert([elements count] == 16, @"Input has wrong number of elements"); 
unsigned index = 0; 
for (NSString *element in elements) { 
    int value = [element intValue]; 
    NSAssert(value >= 0 && value <= 255, @"Element is invalid"); 
    output[index++] = (char)value; 
} 

注意:你應該使用int[],而不是char[],對於output

+0

你可以看到236(輸入)值將被存儲爲意外(由於字符範圍-127到128) – Mani

+0

@Mani只有'char'是* signed *值,情況並非總是如此,但我同意我提到數組應該是'int'而不是'char'。 – trojanfoe

1
NSString *str = @"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45"; 
NSArray *array = [str componentsSeparatedByString:@","]; 

然後在用這個循環或東西添加到您的字符數組:

char* myLilChar = [[array objectAtIndex:i] UTF8String]; 

乾杯:)

1

如果你想爲你說的是​​,使用下面

NSString *str = @"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45"; 
NSArray *array = [str componentsSeparatedByString:@","]; 
unsigned char keyPtr[array.count]; 
for(int i=0;i<array.count;i++) 
    keyPtr[i] = (unsigned char)[[array objectAtIndex:i] intValue]; 
+0

@trojanfoe我已經更新了我的答案。這是什麼意思?我沒有明白。 – Mani

+0

@trojanfoe我已更新我的代碼。 – Mani