Okay, so this is a bit confusing (well to me). I have a string that has a single number I want out of it. I have surrounded this number with \'/\' so that I will be able to
Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);
I think you have confusion in syntax of NSMakeRange. It is something like this
NSMakeRange(<#NSUInteger loc#>, <#NSUInteger len#>)
<#NSUInteger loc#>:
It is the location from where you want to start picking or substring.
<#NSUInteger len#>:
This is the length of your output or substring.
Example:
Mytest12test
Now I want to pick'12'
so:
NSString *t=@"Mytest12test";
NSString *x=[t substringWithRange:NSMakeRange(6, 2)] ;
In your code instead of length you are passing index of end character that is your mistake.
When the compiler runs into this code...
else{
end = i + 1;
}
... in the last iteration of the loop, it sets the end variable to one more then the range of MYSTRING
. This is why you are getting that error. To fix it, just do this:
else{
end = i;
}
Hope this helps!
P.S. Saleh's approach is a simpler way of accomplishing what you want
------UPDATE------
You should do it like this actually:
NSMutableArray *occurencesOfSlashes = [[NSMutableArray alloc] init];
char looking = '/';
for(int i=0; i < MYSTRING.length; i++){
if ([MYSTRING characterAtIndex:i] == looking) {
[occurencesOfSlashes addObject:[NSNumber numberWithInt:i]];
}
NSString *finalString = [MYSTRING substringWithRange:NSMakeRange([occurencesOfSlashes objectAtIndex:0],[occurencesOfSlashes objectAtIndex:1])];
I don't know why your are using this approach, but iOS provides a string function which separates a string with respect to another string and returns an array of the components. See the following example:
NSString * str = @"dadsada/2/dsadsa";
NSArray *listItems = [str componentsSeparatedByString:@"/"];
NSString *component = [listItems objectAtIndex:1];
Now your component string should have 2 store in it.