查找字符串的子字符串范围 [英] find range of substring of string

查看:141
本文介绍了查找字符串的子字符串范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在字符串中获取一系列子字符串。按范围我的意思是子串开始的位置和结束的位置。所以如果我有以下字符串示例:

I am trying to figure out how to get a range of a substring within a string. By range I mean where the substring begins and where it ends. So if I have following string example:

NSString *testString=@"hello everyone how are you doing today?Thank you!";

如果我要查找的子字符串(在此示例中)是你好吗,那么起始范围应为15,结束范围应为31.

If the substring I am looking for (in this example) is "how are you doing", then the beginning range should be 15 and the ending range should 31.

  (15, 31)

谁能告诉我如何以编程方式执行此操作?谢谢!

Can anyone tell me how I could do this programatically? Thank you!

推荐答案

您可以使用 -rangeOfString 方法查找字符串中子字符串的位置。然后,您可以将范围的位置与NSNotFound进行比较,以查看字符串是否确实包含子字符串。

You can use the method -rangeOfString to find the location of a substring in a string. You can then compare the location of the range to NSNotFound to see if the string actually does contain the substring.

NSRange range = [testString rangeOfString:@"how are you doing"];

if (range.location == NSNotFound) {
    NSLog(@"The string (testString) does not contain 'how are you doing' as a substring");
}
else {
    NSLog(@"Found the range of the substring at (%d, %d)", range.location, range.location + range.length);        
}

这篇关于查找字符串的子字符串范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆