ios - Clipping NSString based on length + range of string -
i have large nsstring trim:
this example of long string
first trim word or words. example, pick word "long". achieve this:
nsrange textrange = [[theentirestring lowercasestring] rangeofstring:@"long"]; nsstring *substring = //do individual word(s)??
which result in:
long
however, need 10 characters in final result. in case final result want achieve is:
my long st
as can see, evenly add characters on left , right side of word until reach desired character count, placing word or words in middle.
any appreciated.
as long string doesn't contain defined separator more once, should see right:
nsstring *string = @"this example of long string."; nsstring *separator = @"long"; nsinteger desiredlength = 10; nsrange range = [[string lowercasestring] rangeofstring:separator]; if(range.location != nsnotfound) { nsinteger remainder = (desiredlength - [separator length]); nsinteger halfremainder = (remainder / 2); range = nsmakerange((range.location - halfremainder), (range.length + remainder)); nsstring *result = [string substringwithrange:range]; nslog(@"result: %@", result); }
result: long st
this should customisable suit needs.
also, might worth checking halfremainder isn't trying divide odd number (i.e. 5 / 2) cast integer may cause isses out of range exceptions.
Comments
Post a Comment