2010-08-20 24 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