2015-10-15 25 views
2

我試圖從firstname + lastname中獲取名字和姓氏。將charAtIndex分配給stringWithCharacters會導致無效的投射警告和訪問錯誤

int loop=0; 
NSMutableString *firstname = [[NSMutableString alloc]init]; 
NSMutableString *fullName = [[NSMutableString alloc]initWithString:@"Anahita+Havewala"]; 

for (loop = 0; ([fullName characterAtIndex:loop]!='+'); loop++) { 
    [firstname appendString:[NSString stringWithCharacters:(const unichar *)[fullName characterAtIndex:loop] length:1]]; 
} 
NSLog(@"%@",firstname); 

我試圖從類型轉換爲unichar爲const單字符*因爲characterAtIndex返回一個單字符,但stringWithCharacters接受一個const單字符。

這會導致從較小的整數類型警告轉換,並遇到此行時應用程序崩潰(訪問不良)。

爲什麼Objective C中的字符串操作如此複雜?

回答

0

嘗試了這一點:

NSMutableString *firstname = [[NSMutableString alloc] init]; 
    NSMutableString *fullName = [[NSMutableString alloc] initWithString:@"Anahita+Havewala"]; 

for (NSUInteger loop = 0; ([fullName characterAtIndex:loop]!='+'); loop++) { 
    unichar myChar = [fullName characterAtIndex:loop]; 
    [firstname appendString:[NSString stringWithFormat:@"%C", myChar]]; 
} 

NSLog(@"%@", firstname); 
+0

您的解決方案一如既往地出色。謝謝! – SeeObjective

+0

總是樂於幫助!很高興它幫助你:)! – Abhinav

+0

不知道爲什麼我在這裏得到了投票。請發佈投票的理由! – Abhinav

1

您可以很容易地得到名字和最後使用componentsSeparatedByString:方法。

NSMutableString *fullName = [[NSMutableString alloc]initWithString:@"Anahita+Havewala"]; 
NSArray *components = [fullName componentsSeparatedByString:@"+"]; 
NSString *firstName = components[0]; 
NSString *lastName = components[1]; 

注:你需要做適當的數組邊界檢查。您也可以使用NSScanner來達到同樣的目的。

+0

我會怎麼做一個數組邊界檢查?我不知道'+'之前或之後會有多少個角色。如果我需要找出來,我不得不使用characterAtIndex。 – SeeObjective

相關問題