Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find range of substring of string

Tags:

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!"; 

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!

like image 404
Teddy13 Avatar asked Jun 08 '13 10:06

Teddy13


People also ask

What is range of string?

Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string.

How do you find the range of a string in Python?

You can get a range of characters(substring) by using the slice function. Python slice() function returns a slice object that can use used to slice strings, lists, tuples. You have to Specify the parameters- start index and the end index, separated by a colon, to return a part of the string.

What is substring of a string?

A substring is a subset or part of another string, or it is a contiguous sequence of characters within a string. For example, "Substring" is a substring of "Substring in Java."


1 Answers

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);         } 
like image 169
max_ Avatar answered Sep 17 '22 13:09

max_