Substring with range out of bounds?

情到浓时终转凉″ 提交于 2019-11-29 13:41:27

Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);

Iducool

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.

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.

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])];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!