拆分 NSString 并限制响应 [英] Split NSString and Limit the response
问题描述
我有一个字符串 Hello-World-Test,我只想用第一个破折号分割这个字符串.
I have a string Hello-World-Test, I want to split this string by the first dash only.
字符串 1:你好字符串 2:世界测试
String 1:Hello String 2:World-Test
这样做的最佳方法是什么?我现在正在做的是使用 componentsSeparatedByString,获取数组中的第一个对象并将其设置为字符串 1,然后使用字符串 1 的长度作为起始索引执行子字符串.
What is the best way to do this? What I am doing right now is use componentsSeparatedByString, get the first object in the array and set it as String 1 then perform substring using the length of String 1 as the start index.
谢谢!
推荐答案
我在 NSString
上添加了一个类别,以便在给定字符串的第一次出现时进行拆分.以数组形式返回结果可能并不理想,但除此之外似乎还可以.它只是使用了 NSString
方法 rangeOfString:
,它接受一个 NSString
(B) 并返回一个 NSRange
显示在哪里该字符串(B)位于.
I added a category on NSString
to split on the first occurrence of a given string. It may not be ideal to return the results in an array, but otherwise it seems fine. It just uses the NSString
method rangeOfString:
, which takes an NSString
(B) and returns an NSRange
showing where that string(B) is located.
@interface NSString (Split)
- (NSArray *)stringsBySplittingOnString:(NSString *)splitString;
@end
@implementation NSString (Split)
- (NSArray *)stringsBySplittingOnString:(NSString *)splitString
{
NSRange range = [self rangeOfString:splitString];
if (range.location == NSNotFound) {
return nil;
} else {
NSLog(@"%li",range.location);
NSLog(@"%li",range.length);
NSString *string1 = [self substringToIndex:range.location];
NSString *string2 = [self substringFromIndex:range.location+range.length];
NSLog(@"String1 = %@",string1);
NSLog(@"String2 = %@",string2);
return @[string1, string2];
}
}
@end
这篇关于拆分 NSString 并限制响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!