【问题标题】:Get range substring from existing string从现有字符串中获取范围子字符串
【发布时间】:2015-07-07 09:53:23
【问题描述】:

我有一个NSString,我想通过定位一个单词来创建一个子字符串。

例如,我的字符串是:@"text13 text12 text and new value" 但是当我通过编程搜索“文本”时,它的返回范围是 范围=位置=0,长度=4 但它应该是“文本”字符串的返回范围,它意味着位置 15 到长度 4

NSString *string = @"text13 text12 text";
NSString *searchStr = @"text";
NSRange range = [string rangeOfString:searchStr];

谁能帮帮我或举个例子?

谢谢, 寿司

【问题讨论】:

  • 您应该说出描述您的字符串的内容,即允许将其定义为“要找到的文本”的分隔符。空间?标点符号?还有什么?
  • 假设,如果我要搜索“文本”,那么我需要相同到相同匹配字符串的范围,因为这里是 text13 和 text 13 ,但我不想要这个范围,

标签: ios objective-c


【解决方案1】:

你可以这样做:

[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                           options:NSStringEnumerationByWords | NSStringEnumerationLocalized
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
     // this enumerate all the "words" of your string
     if ([string isEqualToString: searchString]) {
        // use substringRange, the range of your string
        // if you need only the first occurrence, then exit from block, otherwise continue
     }
}

【讨论】:

  • 啊!非常感谢。它工作正常,你能告诉我一件事吗?
  • 假设我有一个字符串,字符串是@"hi this objective c\"我想找到,这是子字符串\"";但我想查找“我想查找,这是子字符串”的范围,仅从总字符串中,我想按“”(双引号字符)搜索
  • 对不起,我没有理解你的问题。请改写一下好吗?
  • 这是我的字符串:NSString *string = @"hi this objective c and \"hello swift\"";但我想找到'hello swift'字符串的范围,因为它在另一个字符串中更简单一个字符串(hello swift)......请帮助我
  • 在这种情况下,我认为您应该使用 rangeOfString 方法简单地搜索整个子字符串,而不是像我的回答那样搜索单词。由于双引号与string中的任何其他字符一样,因此以这种方式搜索应该不会产生任何问题。
猜你喜欢
  • 2021-03-10
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 2013-06-04
  • 2015-08-21
  • 1970-01-01
相关资源
最近更新 更多