我是Objective-c的新手 让我们假设我有一个像这样的字符串
NSString* s = @"assets-library://asset/asset.MOV? id=100000009&ext=MOV"
如何从中获取“ext =”(本例中为“MOV”)的内容?我怎么把它转换成大写(所以“mov” - >“MOV”),以防它还没有呢?
答案 0 :(得分:3)
您可以使用NSString componentsSeparatedByString方法将字符串分解为数组:
NSString *sourceString = @"assets-library://asset/asset.MOV? id=100000009&ext=MOV";
NSArray *stringChunks = [sourceString componentsSeparatedByString:@";ext="];
NSString *outString = [[stringChunks objectAtIndex:1] uppercaseString];
<强>更新强>
正如我在下面的评论中所述,这是一个蠢货。 (如果在“ext =”之后有一个参数,它将失败)因此,这是使用NSURL的更强大的实现。 (有点毫无意义,必须说。)我假设您的代码中原始URL中的空格字符是拼写错误,如果不是使用stringByReplacingOccurrencesOfString将其交换出来,如下所示。
// Create a URL based on a cleaned version of the input string.
NSString *sourceString = @"assets-library://asset/asset.MOV?id=100000009&ext=MOV";
NSURL *sourceURL = [NSURL URLWithString:[sourceString stringByReplacingOccurrencesOfString:@"&" withString:@"&"]];
NSArray *pathComponents = [[sourceURL query] componentsSeparatedByString:@"&"];
// Create a dictionary of the key/value portions of the query string.
NSMutableDictionary *queryParameters = [[NSMutableDictionary alloc] init];
for (NSString *component in pathComponents) {
[queryParameters setObject:[[component componentsSeparatedByString:@"="] objectAtIndex:1]
forKey:[[component componentsSeparatedByString:@"="] objectAtIndex:0]];
}
// Fetch the contents of the "ext" key and force to uppercase.
// We should really check that objectForKey doesn't return nil, but this is just
// an example.
NSString *outString = [[queryParameters objectForKey:@"ext"] uppercaseString];
[queryParameters release];
答案 1 :(得分:0)
您可能需要查看NSURL,它明确支持解析URL字符串。