Monday, May 20, 2013

NSString substringToIndex example ios


[NSString substringToIndex]

Returns a new string containing the characters of the receiver up to, but not including, the one at a given index.
- (NSString *)substringToIndex:(NSUInteger)anIndex
Parameters
anIndex
An index. The value must lie within the bounds of the receiver, or be equal to the length of the receiver.

Important: Raises an NSRangeException if (anIndex - 1) lies beyond the end of the receiver.
Return Value of [NSString substringToIndex]
A new string containing the characters of the receiver up to, but not including, the one at anIndex. If anIndex is equal to the length of the string, returns a copy of the receiver.
Example of [NSString substringToIndex]
NSString *param = nil;
NSRange start = [string rangeOfString:@"id=%"];
if (start.location != NSNotFound)
{
    param = [string substringFromIndex:start.location + start.length];
    NSRange end = [param rangeOfString:@"%"];
    if (end.location != NSNotFound)
    {
        param = [param substringToIndex:end.location];
    }
}

Example of [NSString substringToIndex]
NSString *fullString = /* obtain from somewhere */;
NSString *prefix = nil;

if ([fullString length] >= 3)
    prefix = [fullString substringToIndex:3];
else
    prefix = fullString;
Example of [NSString substringToIndex]
float inchesInField = [sizeField.text floatValue];
float shoeSize = inchesInField * 3 - 22;
NSMutableString *appendedShoeSize = [[NSMutableString alloc] initWithFormat:@"%.1f", shoeSize];

if ([appendedShoeSize hasSuffix:@".3"] || [appendedShoeSize hasSuffix:@".5"] || [appendedShoeSize hasSuffix:@".4"] || [appendedShoeSize hasSuffix:@".6"]) {

    appendedShoeSize = [[appendedShoeSize substringToIndex:[appendedShoeSize length] - 2] mutableCopy];
    [appendedShoeSize appendString:@" ½"];
} 

if ([appendedShoeSize hasSuffix:@".0"] || [appendedShoeSize hasSuffix:@".1"] || [appendedShoeSize hasSuffix:@".2"]) {

    appendedShoeSize = [[appendedShoeSize substringToIndex:[appendedShoeSize length] - 2] mutableCopy];
}