2012-12-19 62 views
-2

我有一个NSString &我想从中删除一些字符,当在其中找到第一个逗号时。当找到第一个逗号时,从NSString中删除字符

ex. str = @"0,1,2,3"; 
output - > str = @"1,2,3"; 

如何做到这一点。任何人都可以帮助我解决这个问题。

+0

我会使用你可以在这里找到的方法http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/CreatingStrings.html#//apple_ref/doc/uid/20000148- SW5 – dasdom

+0

请检查我的答案和评论,它与您之前使用2个字符串的questin几乎相似。 –

+3

@Girish为什么不努力阅读文档并试图找出有用的东西?这是一个微不足道的任务... – 2012-12-19 16:48:01

回答

3

通用的案例:

NSString* str= @"0,1,2,3"; 
NSRange range= [str rangeOfString: @","]; 
if(range.location!=NSNotFound) 
{ 
    str= [str substringWithRange: NSMakeRange(range.location+1, str.length-range.length-1)]; 
    NSLog(@"%@",str); 
} 

它不创建崩溃如果字符串不是一个逗号。

2
NSMutableArray *arr1 = [[str1 componentsSeparatedByString:@","] mutableCopy]; 
if ([arr1 count]){ 
    [arr1 removeObjectAtIndex:0]; 
} 
NSString *finalStr = [arr1 componentsJoinedByString:@","]; 
6

请与下面的代码:

NSMutableArray *tempArray=[[NSMutableArray alloc]initWithArray:[yourString componentsSeparatedByString:@","]]; 
if([tempArray count] > 0) 
{ 
    [tempArray removeObjectAtIndex:0]; 
} 
NSString *output=[tempArray componentsJoinedByString:@","]; 
+0

是不是说在所有情况下数组数都大于零。 –

+0

@RamyAlZuhouri:感谢您的评论,我编辑了我的答案 –

1

试试这个:

NSString *[email protected]"0,1,2,3"; 
NSMutableArray *arr1=[[NSMutableArray alloc]initWithArray:[str1 componentsSeparatedByString:@","]]; 
if([arr1 count]>1)[arr1 removeObjectAtIndex:0];//as 1st comma is found. means atleast 2 elements must be there. 
NSString *finalString=[arr1 componentsJoinedByString:@","]; 

注意:这不是一个编译和checked..I刚才输入记事本窗口。