开发者

Getting a value from string

开发者 https://www.devze.com 2023-02-03 16:22 出处:网络
Im new to objective-c Lets assume I have a string such as this NSString* s = @\"assets-library://asset/asset.MOV? id=100000009&ext=MOV\"

Im new to objective-c Lets assume I have a string such as this

NSString* s = @"assets-library://asset/asset.MOV? id=100000009&ext=MOV"

how do I get the contents of the "ext=" ("MOV" in this case) out of 开发者_Go百科it? How do I convert it to uppercase(so "mov" -> "MOV") in case it is not already so?


You could use the NSString componentsSeparatedByString method to decompose the string into an array as such:

NSString *sourceString = @"assets-library://asset/asset.MOV? id=100000009&ext=MOV";
NSArray *stringChunks = [sourceString componentsSeparatedByString:@";ext="];
NSString *outString = [[stringChunks objectAtIndex:1] uppercaseString];

UPDATE

As I stated in my comment below, this is a kludge. (It'll fail if there's an argument after the "ext=") As such, here's a more robust implementation using NSURL. (Somewhat pointlessly it has to be said.) I've presumed that the space character in the original URL in your code is a typo, if not swap it out using the stringByReplacingOccurrencesOfString as per below.

// 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];


You may want to look into NSURL, which has explicit support for parsing URL strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消