【问题标题】:Position of a Substring in NSStringNSString 中子字符串的位置
【发布时间】:2012-06-28 06:54:48
【问题描述】:

如何在NSString 中获取子字符串的位置/索引?

我正在通过以下方式找到位置。

NSRange range = [string rangeOfString:searchKeyword];
NSLog (@"match found at index:%u", range.location);

当searchKeyword 是string 中的子字符串时,这将返回index:2147483647。

我怎样才能得到像 20 或 5 这样的索引值?

【问题讨论】:

    标签: iphone objective-c ios xcode ios4


    【解决方案1】:

    2147483647 与NSNotFound 相同,表示未找到您搜索的字符串 (searchKeyword)。

    NSRange range = [string rangeOfString:searchKeyword];
    if (range.location == NSNotFound) {
        NSLog(@"string was not found");
    } else {
        NSLog(@"position %lu", (unsigned long)range.location);
    }
    

    【讨论】:

    • 感谢 -@Kevin Ballard 的帮助。你帮我看看我如何在该范围的基础上选择一个子字符串。例如And, of course, it must be asked:is it proper to transact with the Turks for the most reassured of Greek possessions when **Greece* is under Turkish invasion and subjugation?。在这里我找到了希腊的位置,现在我想在那个希腊词之前和之后选择一个substring 一个或两个词。喜欢when Greece is Under Turkish。你能帮忙吗?
    • @ShaheenRehman:您可能想使用-enumerateSubstringsInRange:options:usingBlock: API。这可以给你个别的话。
    • -@Kevin Ballard 你能给我-enumerateSubstringsInRange:options:usingBlock: API 的代码示例吗?
    【解决方案2】:
    NSString *searchKeyword = @"your string";
    
    NSRange rangeOfYourString = [string rangeOfString:searchKeyword];
    
    if(rangeOfYourString.location == NSNotFound)
    {
         // error condition — the text searchKeyword wasn't in 'string'
    }
    else{
         NSLog(@"range position %lu", rangeOfYourString.location);
    }
    
    NSString *subString = [string substringToIndex:rangeOfYourString.location];
    

    希望对你有帮助....

    【讨论】:

    • 感谢 -@Kevin Ballard 的帮助。你帮我看看我如何在该范围的基础上选择一个子字符串。例如And, of course, it must be asked:is it proper to transact with the Turks for the most reassured of Greek possessions when **Greece* is under Turkish invasion and subjugation?. 在这里我找到了希腊的位置,现在我想在那个希腊词的前后选择一个 substring 一个或两个词。喜欢when Greece is Under Turkish。你能帮忙吗?
    • 你可以使用它.... [string substringToIndex:rangeOfYourString.location];我正在编辑代码...可能会对您有所帮助
    • 谢谢-@Abhishek 它对我有用[string substringFromIndex:range.location];
    猜你喜欢
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 2015-03-30
    • 1970-01-01
    相关资源
    最近更新 更多