繁体   English   中英

目标C-通过查找字符的第一次和第二次出现来提取子字符串

[英]Objective C - Extract substring by finding first and second occurrence of a character

我正在尝试将我的Android应用程序移植到iOS。 我需要提取出现在单引号'字符的第一次和第二次出现之间的字符串。

例如,从javascript:popUpWindow7('news_details.asp?slno=2029',620,300,100,100,'yes') ,我需要提取news_details.asp?slno=2029

在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)));

我在Objective 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]];

我究竟做错了什么?

代码的问题在于,范围的length是从位置0开始计算的,而不是从范围的location 范围的length不是范围终点的索引,而是范围的起始位置与其终点之间的距离。

如何将其作为更简单的选择:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM