如何在第一个字符实例后删除部分NSString?

时间:2013-09-17 21:15:27

标签: ios objective-c nsstring

我想删除部分NSString

在以下字符串中我想在“/ sampletext1 / sampletext2 / sampletext3”之前抓取数字

1464/sampletext1/sampletext2/sampletext3

我已经在数字之前删除了网址,但无法弄清楚其余部分。有时数字可能是3或4或5位数。

感谢

3 个答案:

答案 0 :(得分:6)

获取第一个/字符的索引,然后获取到该位置的子字符串。

NSString *stuff = @"1464/sampletext1/sampletext2/sampletext3";
NSString *digits;
NSRange slashRange = [stuff rangeOfString:@"/"];
if (slashRange.location != NSNotFound) {
    digits = [stuff substringToIndex:slashRange.location];
} else {
    digits = stuff;
}

答案 1 :(得分:3)

您提到您从前面提取了一个网址,因此我猜测您正在处理http://localhost:12345/a/b/chttp://localhost/12345/a/b/c之类的内容。

在任何一种情况下,您都可以将字符串转换为NSURL并利用其内置功能:

// Port
NSURL *URL = [NSURL URLWithString:@"http://localhost:12345/a/b/c"];
NSUInteger port = URL.port.integerValue;

// Path component
NSURL *URL = [NSURL URLWithString:@"http://localhost/12345/a/b/c"];
NSString *number = URL.pathComponents[1];

答案 2 :(得分:0)

使用正则表达式:

NSError *error;
NSString *test = @"1464/sampletext1/sampletext2/sampletext3";
NSRegularExpression *aRegex = [NSRegularExpression regularExpressionWithPattern:@"^\\d+"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:&error];

NSRange aRangeOfFirstMatch = [aRegex rangeOfFirstMatchInString:test options:0 range:NSMakeRange(0, [test length])];

if (aRangeOfFirstMatch.location != NSNotFound) {
    NSString *matchedString = [test substringWithRange:aRangeOfFirstMatch];
    NSLog(@"matchedString = %@", matchedString);
}