简体   繁体   English

iPhone SDK inString函数

[英]iPhone SDK inString Function

Im trying to write a method that will pull out the ID from a URI String. 我正在尝试编写一种将从URI字符串中提取ID的方法。 My code below seems inefficient, what would be a better way of finding the id string? 我的以下代码似乎效率低下,找到ID字符串的更好方法是什么?

NSString *aID = [[[NSString alloc] initWithString:@"http://www.example.com/id368907840?mt=8&uo=4"] autorelease];
NSArray *arrStr = [aID componentsSeparatedByString:@"/id"];
aID = [arrStr objectAtIndex:1];
arrStr = [aID componentsSeparatedByString:@"?mt="];
aID = [arrStr objectAtIndex:0];

The above leaves me with the NSString = 368907840 上面让我留着NSString = 368907840

You can use NSURL -lastPathComponent , NSString -stringByTrimmingCharactersInSet , and NSCharacterSet +letterCharacterSet to accomplish the same task as in the following example: 您可以使用NSURL -lastPathComponentNSString -stringByTrimmingCharactersInSetNSCharacterSet + letterCharacterSet来完成与以下示例相同的任务:

NSURL* url = [NSURL URLWithString:@"http://www.example.com/id368907840?mt=8&uo=4"];
NSString* lastpath = [url lastPathComponent]; // "id368907840"
NSCharacterSet* letters = [NSCharacterSet letterCharacterSet];
NSString* result = [lastpath stringByTrimmingCharactersInSet:letters]; // 368907840

Disclaimer: I haven't actually tried this, so you will need to try it yourself, but I believe this should work. 免责声明:我实际上并没有尝试过,所以您需要自己尝试一下,但是我相信这应该可行。

You could use a combination of subStringWithRange and rangeOfString, something along the lines of 您可以结合使用subStringWithRange和rangeOfString,类似

NSString *aID = [[[NSString alloc] initWithString:@"http://www.example.com/id368907840?mt=8&uo=4"] autorelease];

int startIndex = [aID rangeOfString:@"id"].location + 2;
int length = [aID rangeOfString:@"mt"].location - startIndex - 1;

aID = [aID substringWithRange:NSMakeRange(startIndex, length)];

Use regular expressions. 使用正则表达式。 One of those cases where it's easier and more readable to use them. 使用它们更容易且更具可读性的情况之一。

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

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