Objective C - 通过查找第一个和第二个字符来提取子字符串

问题描述:

我试图将我的Android应用程序移植到iOS。我需要提取第一个和第二个单引号'字符之间出现的字符串。例如,从javascript:popUpWindow7('news_details.asp?slno=2029',620,300,100,100,'yes'),我需要提取news_details.asp?slno=2029Objective C - 通过查找第一个和第二个字符来提取子字符串

在Java中,我这样做:

String inputUrl = "javascript:popUpWindow7('news_details.asp?slno=2029',620,300,100,100,'yes')"; 
StringBuilder url = new StringBuilder(); 
url.append(inputUrl.substring(inputUrl.indexOf('\'')+1, 
       inputUrl.indexOf('\'',inputUrl.indexOf('\'')+1))); 

我无法找到目标C类似的indexOf任何方法,所以我做了以下内容:

NSUInteger length =0; 
NSMutableString* url; 

NSString* urlToDecode = @"javascript:popUpWindow7('news_details.asp?slno=2029',620,300,100,100,'yes')"; 

for (NSInteger i=[urlToDecode rangeOfString:@"\'"].location +1; i<urlToDecode.length; i++) { 

    if([urlToDecode characterAtIndex:i]== '\'') 
    { 
     length = i; 
     break; 
    } 
} 

NSRange range = NSMakeRange([urlToDecode rangeOfString:@"\'"].location +1, length); 

[url appendString:[urlToDecode substringWithRange:range]]; 

我在做什么错?

+0

虽然妥善的解决办法可能会涉及到一个'NSScanner'或正则表达式,没有推荐它,如果你的字符串都保证有这种形式的简单拆分可以做的工作:'[urlToDecode componentsSeparatedByString:@“'”] [1]' – Alladinian

您的代码存在的问题是,您的范围的length从位置零开始计数,而不是从范围的location开始计数。范围的length不是范围末尾的索引,而是范围起始位置与其结束之间的距离。

这个怎么样作为一个简单的选择:

NSArray *components = [urlToDecode componentsSeparatedByString:@"'"]; 
if (components.count > 1) 
{ 
    NSString *substring = components[1]; 
} 
+0

这绝对有效!谢谢 –