Position of a Substring in NSString
34,823
Solution 1
2147483647
is the same thing as NSNotFound
, which means the string you searched for (searchKeyword
) wasn't found.
NSRange range = [string rangeOfString:searchKeyword];
if (range.location == NSNotFound) {
NSLog(@"string was not found");
} else {
NSLog(@"position %lu", (unsigned long)range.location);
}
Solution 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];
may this will help you....
Author by
Shaheen Rehman
I m new in Iphone Application. i hope that i will got benefits from this site. Thanks
Updated on June 28, 2020Comments
-
Shaheen Rehman almost 4 years
How I can get the position/Index of a substring within an
NSString
?I am finding the location in the following way.
NSRange range = [string rangeOfString:searchKeyword]; NSLog (@"match found at index:%u", range.location);
This returns
index:2147483647
whensearchKeyword
is a substring withinstring
.How i can get the index value like
20
or5
like that? -
Shaheen Rehman almost 12 yearsthanks -@Kevin Ballard for help. do you help me that how i can select a substring on the bases of that range. e.g.
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?
. here i found the location of Greece now i want to select asubstring
one or two words before and after of that Greece Words. likewhen Greece is Under Turkish
. can you help Please! -
Shaheen Rehman almost 12 yearsthanks -@Kevin Ballard for help. do you help me that how i can select a substring on the bases of that range. e.g.
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?.
here i found the location of Greece now i want to select asubstring
one or two words before and after of that Greece Words. likewhen Greece is Under Turkish
. can you help Please! -
Abhishek almost 12 yearsyou can use it.... [string substringToIndex:rangeOfYourString.location]; I am editing in the code... may this will help you
-
Lily Ballard almost 12 years@ShaheenRehman: You probably want to use the
-enumerateSubstringsInRange:options:usingBlock:
API. This can give you individual words. -
Shaheen Rehman almost 12 yearsthanks -@Abhishek it work for me
[string substringFromIndex:range.location];
-
Shaheen Rehman almost 12 years-@Kevin Ballard can you give me code example of
-enumerateSubstringsInRange:options:usingBlock:
API.