2010-08-20 23 views
0

嗨我有一個用分隔符「:」分隔的字符串數組。我嘗試使用componentsSeparatedByString方法分離字符串,然後將結果保存到數組中,稍後使用該數組生成所需的輸出,但它沒有奏效。目標C(iPhone)中的拆分和交換字符串

例如

現在我的UITableView顯示細胞:

案例1:

How:Many 
Too:Many 
Apple:Milk 
iPhone:Simulator 

我想顯示在UITableView中的細胞:

案例2:

Many How 
Many Too 
Milk Apple 
Simulator iPhone 

這是我的cellForRowAtIndexPath方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 
NSString *entry=[entryKeys objectAtIndex:[indexPath section]]; 
    NSArray *entrySection=[entries objectForKey:entry]; 
    cell.textLabel.text=[entrySection objectAtIndex:[indexPath row]] 
} 

return cell; 
} 

上述方法的輸出是殼體1但我想輸出爲殼體2個 entryKeys具有從AZ和入口段鍵有價值分類和列出的各自的鍵,即條目開始與A組合在關鍵A等...

它可能聽起來很愚蠢,但我仍然在學習..請幫助我

回答

3

有很多方法可以做到這一點。這是一個;

// get your raw text in the form of "AAA:BBB" 
NSString *rawText = [entrySection objectAtIndex:[indexPath row]]; 

// split the text by the : to get an array containing { "AAA", "BBB" } 
NSArray *splitText = [rawText componentsSeparatedByString:@":"]; 

// form a new string of the form "BBB AAA" by using the individual entries in the array 
NSString *cellText = [NSString stringWithFormat:@"%@ %@", [splitText objectAtIndex:1], [splitText objectAtIndex:0]]; 

希望有幫助。

+0

哇..那麼工作..我做的錯誤是在分離字符串後,我直接將它分配給單元格textlabel,在那裏我得到outofbounds例外..謝謝你.. – racharambola 2010-08-20 21:45:56

0

會不會stringByReplacingOccurrencesOfString:withString:更容易?

+0

這並不反轉拆分元素,作爲OP想要。 – 2010-08-20 21:45:51

+0

感謝您的回覆..上述方法有效.. – racharambola 2010-08-20 21:46:56

+0

真實,我的錯誤 – rano 2010-08-20 21:48:30