NSString从字符串中检索子字符串

NSString从字符串中检索子字符串

本文介绍了IOS:NSString从字符串中检索子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿我正在寻找一种从另一个字符串中提取字符串的方法。它可以是任何长度并且位于字符串的任何部分,因此通常的方法不起作用。

Hey I am looking for a way to extract a string from another string. It could be any length and be in any part of the string so the usual methods don't work.

例如

我要提取的是从id =%到下一个%。

What I want to extract is from id=% to the next %.

任何想法都是?

推荐答案

使用rangeOfString方法:

Use the rangeOfString method:

NSRange range = [string rangeOfString:@"id=%"];
if (range.location != NSNotFound)
{
   //range.location is start of substring
   //range.length is length of substring
}

然后你可以使用 substringWithRange来切断字符串: substringFromIndex: substringToIndex:获取所需位的方法。以下是您特定问题的解决方案:

You can then chop up the string using the substringWithRange:, substringFromIndex: and substringToIndex: methods to get the bits you want. Here's a solution to your specific problem:

NSString *param = nil;
NSRange start = [string rangeOfString:@"id=%"];
if (start.location != NSNotFound)
{
    param = [string substringFromIndex:start.location + start.length];
    NSRange end = [param rangeOfString:@"%"];
    if (end.location != NSNotFound)
    {
        param = [param substringToIndex:end.location];
    }
}

//param now contains your value (or nil if not found)

或者,这是从URL中提取查询参数的一般解决方案,如果您需要多次执行此操作,这可能更有用:

Alternatively, here's a general solution for extracting query parameters from a URL, which may be more useful if you need to do this several times:

- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
    NSString *queryString = [URL query];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    NSArray *parameters = [queryString componentsSeparatedByString:@"&"];
    for (NSString *parameter in parameters)
    {
        NSArray *parts = [parameter componentsSeparatedByString:@"="];
        if ([parts count] > 1)
        {
            NSString *key = [parts[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *value = [parts[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            result[key] = value;
        }
    }
    return result;
}

这不会从值中删除%字符,但你可以做与

This doesn't strip the % characters from the values, but you can do that either with

NSString *value = [[value substringToIndex:[value length] - 1] substringFromIndex:1];

或类似

NSString *value = [value stringByReplacingOccurencesOfString:@"%" withString:@""];






更新: As iOS 8+的内置类是一个名为 NSURLComponents 的内置类,它可以自动为您解析查询参数( NSURLComponents 可用在iOS 7+上,但查询参数解析功能不是。)


UPDATE: As of iOS 8+ theres a built-in class called NSURLComponents that can automatically parse query parameters for you (NSURLComponents is available on iOS 7+, but the query parameter parsing feature isn't).

这篇关于IOS:NSString从字符串中检索子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:44