Objective-C:从 NSString 中提取子字符串的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1612337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C: Best way to extract substring from NSString?
提问by ThyPhuong
I have a space-separated string like @"abc xyz http://www.example.com aaa bbb ccc".
我有一个空格分隔的字符串,如@"abc xyz http://www.example.com aaa bbb ccc".
How can I extract the substring @"http://www.example.com"from it?
如何从中提取子字符串@"http://www.example.com"?
回答by Justin
I know this is a very late reply, but you can get the substring "http://www.abc.com" with the following code:
我知道这是一个很晚的回复,但您可以使用以下代码获取子字符串“http://www.abc.com”:
[@"abc xyz http://www.abc.com aaa bbb ccc" substringWithRange:NSMakeRange(8, 18)]
Of course, you can still use an NSStringfor that.
当然,您仍然可以使用 an NSString。
回答by Pach
Try this:
尝试这个:
[yourString substringToIndex:<#(NSUInteger)#>];
//or
[yourString substringFromIndex:<#(NSUInteger)#>];
//or
[yourString substringWithRange:<#(NSRange)#>];
回答by Morion
If all of your substrings are separated by spaces, you can try to get an array of substrings using [myString componentsSeparatedByString:@" "]. Then you can check result of
[NSUrl URLWithString:yourSubstring]. It will return nil if the substring isn't a correct link.
如果您的所有子字符串都用空格分隔,您可以尝试使用[myString componentsSeparatedByString:@" "]. 然后你可以检查结果
[NSUrl URLWithString:yourSubstring]。如果子字符串不是正确的链接,它将返回 nil。
回答by rckehoe
Here is my version of the script... Hopefully it's clean and easy to implement. It does a substr of the characters based on limits... Mine is used for a textarea, but can obviously be adapted to textfields :)
这是我的脚本版本...希望它干净且易于实现。它根据限制对字符进行 substr... 我的用于 textarea,但显然可以适应 textfields :)
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
int maxLength = 100;
int currentLength = [self.messageField.text length];
if( currentLength > maxLength )
{
NSString *newMessageText = [self.messageField.text substringWithRange:NSMakeRange(0, maxLength)];
[self.messageField setText:newMessageText];
return NO;
}
else
{
return YES;
}
}
回答by user1873574
This can also try to resolve this issue:
这也可以尝试解决这个问题:
NSArray *data = [@"abc xyz http://www.abc.com aaa bbb ccc" componentsSeparatedByString:@" "];
for(NSString* str in data)
{
if([NSURLConnection canHandleRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]])
NSLog(@"%@",[[NSString alloc ] initWithFormat:@"Found a URL: %@",str]);
}
Hope it helps!
希望能帮助到你!
回答by mmackh
I find PHP's substr()really convenient. Check out my NSString categoryif you're looking to be able to do something like this:
我发现 PHPsubstr()真的很方便。 如果您希望能够执行以下操作,请查看我的NSString 类别:
substr(@"abc xyz http://www.example.com aaa bbb ccc", 8,-12)
or
或者
substr(@"abc xyz http://www.example.com aaa bbb ccc", 8, 18)
Both will give you the result of http://www.example.com
两者都会给你结果 http://www.example.com
Here's a copy of the relevant piece of code:
这是相关代码的副本:
__attribute__((overloadable))
NSString *substr(NSString *str, int start)
{
return substr(str, start, 0);
}
__attribute__((overloadable))
NSString *substr(NSString *str, int start, int length)
{
NSInteger str_len = str.length;
if (!str_len) return @"";
if (str_len < length) return str;
if (start < 0 && length == 0)
{
return [str substringFromIndex:str_len+start];
}
if (start == 0 && length > 0)
{
return [str substringToIndex:length];
}
if (start < 0 && length > 0)
{
return [[str substringFromIndex:str_len+start] substringToIndex:length];
}
if (start > 0 && length > 0)
{
return [[str substringFromIndex:start] substringToIndex:length];
}
if (start > 0 && length == 0)
{
return [str substringFromIndex:start];
}
if (length < 0)
{
NSString *tmp_str;
if (start < 0)
{
tmp_str = [str substringFromIndex:str_len+start];
}
else
{
tmp_str = [str substringFromIndex:start];
}
NSInteger tmp_str_len = tmp_str.length;
if (tmp_str_len + length <= 0) return @"";
return [tmp_str substringToIndex:tmp_str_len+length];
}
return str;
}
回答by ekillaby
If your input string has simple guarantees (for example the guarantee that tokens in the string are always delineated by a space character) then split on the space character and test each element for @"http://"as a prefix.
如果您的输入字符串有简单的保证(例如,保证字符串中的标记始终由空格字符划定),则拆分空格字符并将每个元素@"http://"作为前缀进行测试。
NSString *input = @"abc xyz http://www.example.com aaa bbb ccc";
NSArray *parts = [input componentsSeparatedByString:@" "];
for (NSString *part in parts) {
if ([part hasPrefix:@"http://"]) {
// Found it!
}
}
This can be optimized this based on the application's needs; for example, choose to short-circuit the loop once the element is found or use filters in BlocksKit to get only elements that begin with the prefix. An ideal solution will depend on the nature of the input string and what you're trying to accomplish with it.
这可以根据应用程序的需要进行优化;例如,选择在找到元素后短路循环或使用 BlocksKit 中的过滤器来仅获取以前缀开头的元素。理想的解决方案将取决于输入字符串的性质以及您试图用它完成什么。

