2014-01-24 131 views
0

我有一个关于数组中索引的严重问题。我一直在为此工作2天,但无法找到答案。替换两个字符串之间的字符串

我想这样做,搜索数组中的特定字符,然后将其替换为其他字符串。我正在使用replaceObjectAtIndex方法,但我的代码不起作用。

这是我的代码;

NSString *commentText = commentTextView.text; 
    NSUInteger textLength = [commentText length]; 
    NSString *atSign = @"@"; 
    NSMutableArray *commentArray = [[NSMutableArray alloc] init]; 
    [commentArray addObject:commentText]; 

    for (int arrayCounter=1; arrayCounter<=textLength; arrayCounter++) 
    { 
     NSRange isRange = [commentText rangeOfString:atSign options:NSCaseInsensitiveSearch]; 
     if(isRange.location != NSNotFound) 
     { 
      commentText = [commentText stringByReplacingOccurrencesOfString:commentText withString:atSign]; 
      [_mentionsearch filtrele:_mentionText]; 
      id<textSearchProtocol> delegate; 
      [delegate closeList:[[self.searchResult valueForKey:@"user_name"] objectAtIndex:indexPath.row]]; 
     } 
    } 

好的,现在我可以在文本中找到“@”符号,我可以匹配它。但这是问题的根源,我不能用“@”符号替换任何字符串。这是代码的最后一部分;

-(void)closeList 
    { 
     NSArray *arrayWithSign = [commentTextView.text componentsSeparatedByString:@" "]; 
     NSMutableArray *arrayCopy = [arrayWithSign mutableCopy]; 
     [arrayCopy replaceObjectAtIndex:isRange.location withObject:[NSString stringWithFormat:@"@%@",username]]; 
    } 

当IM日志isRange.location值,它返回正确的。但是当我尝试运行时,我的应用程序崩溃了。所以,我无法替代[NSString stringWithFormat:@“@%@”,用户名]参数。我怎么解决这个问题?

+1

它是如何崩溃?你必须包含崩溃日志。 – jrturton

+0

你为什么试图使用从字符串搜索中取出的范围作为数组的索引? – Wain

+0

没有日志缺陷。只有我有,(lldb)0x6ae8952:jae 0x6ae8962; __pthread_kill + 26. –

回答

2

如果我理解正确,您希望使用新字符串更改字符串中的子字符串。在这种情况下,为什么不直接使用NSString的stringByReplacingOccurrencesOfString方法:

NSString *stringToBeChanged = @"..."; 
NSString *stringToBeChangedWith = @"..."; 
NSString *commentTextNew = [commentText stringByReplacingOccurrencesOfString:stringToBeChanged withString:stringToBeChangedWith]; 
+0

我对数组结果做了很大的错误。这是解决方案thx :) –

+1

我想更改“<>”到< new tring> 之间的字符串我的字符串是他们的动态字符串,那么我如何识别字符串 –

相关问题