Search code examples
iosobjective-cnsstringnscharacterset

trim white space and x number of characters at the end of the string


let us consider this as a string--'Wi-Fi 1234ff'

i would like to trim this as -'wifi'

removing last 6 characters, special characters and space.

what i tried is to remove space-

NSString *trimmedString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

to remove special characters-by pointing ($) what character i want to remove

 NSCharacterSet *trimmedString = [NSCharacterSet characterSetWithCharactersInString:@"$"];
string = [string stringByTrimmingCharactersInSet:trimmedString];

But wondering how could i remove 'x' number of strings from the end.

something like this..

  if ([string length] > 0) {
string = [string substringToIndex:[string length] - x];
 } 

Solution

  • If your goal is to keep everything from the start up to, but not including the 1st space, then try this:

    NSRange spaceRange = [myString rangeOfString:@" "];
    if (spaceRange.location != NSNOtFound) {
        NSString *trimmedString = [myString substringToIndex:spaceRange.location];
        // This gives you @"Wi-Fi"
    }
    

    If, instead, you want to find the last space, change the 1st line to:

    NSRange spaceRange = [myString rangeOfString:@" " options:NSBackwardsSearch];
    

    That will find the last space.