Objective-C:从NSString中提取子字符串的最佳方法?

Thy*_*ong 37 objective-c nsstring

我有一个空格分隔的字符串@"abc xyz http://www.example.com aaa bbb ccc".

如何从中提取子串@"http://www.example.com"

Jus*_*tin 53

我知道这是一个非常晚的回复,但您可以使用以下代码获取子字符串"http://www.abc.com":

[@"abc xyz http://www.abc.com aaa bbb ccc" substringWithRange:NSMakeRange(8, 18)]
Run Code Online (Sandbox Code Playgroud)

当然,你仍然可以使用NSString它.

  • 你只需给它一个不同的范围.最好检查长度`[@"Some string"length]`并将该数字添加到第一个以找到第二个. (2认同)

Pac*_*ach 27

试试这个:

       [yourString substringToIndex:<#(NSUInteger)#>];
//or
      [yourString substringFromIndex:<#(NSUInteger)#>];
//or        
      [yourString substringWithRange:<#(NSRange)#>];
Run Code Online (Sandbox Code Playgroud)


Mor*_*ion 12

如果所有子字符串都用空格分隔,则可以尝试使用子字符串数组[myString componentsSeparatedByString:@" "].然后你可以查看结果 [NSUrl URLWithString:yourSubstring].如果子字符串不是正确的链接,它将返回nil.


rck*_*hoe 5

这是我的脚本版本...希望它干净且易于实现。它根据限制对字符进行 substr ......我的用于文本区域,但显然可以适应文本字段:)

 -(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;

     }

 }
Run Code Online (Sandbox Code Playgroud)