我想修剪一个大的NSString:
this is an example of my long string
首先,我将它修剪成某个词或单词。例如,我选择" long"这个词。为此:
NSRange textRange = [[theEntireString lowercaseString] rangeOfString:@"long"];
NSString *subString = //do something to get the individual word(s)??
哪会导致:
long
但是,我的最终结果需要10个字符。所以在这种情况下,我想要实现的最终结果是:
my long st
如您所见,我在单词的左侧和右侧均匀添加字符,直到达到所需的字符数,将单词放在中间。
非常感谢任何帮助。
答案 0 :(得分:2)
这不会考虑以下字符串,但它应该让你开始。
“long string” - 开头没有字符“
“字符串很长” - 结尾没有字符
“这是一个很长的字符串” - 查询字符串的双重查找
“long” - 少于10个字符
“没有loong的实例” - 没有搜索字符串的实例。
NSString *s = @"this is an example of my long string";
NSString *searchString = @"long";
NSRange range = [[s lowercaseString] rangeOfString:searchString];
range.location -= (10 - (searchString.length)) / 2;
range.length = 10;
NSLog(@"%@", [s substringWithRange:range]);
答案 1 :(得分:1)
只要字符串不多次包含已定义的分隔符,这应该是正确的:
NSString *string = @"This is an example of my 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: my LONG st
这应该是相当可定制的,以满足您的需求。
此外,可能值得检查halfRemainder是不是试图划分奇数(即5/2),因为这会被转换为整数,这可能会导致超出范围异常的isses。
答案 2 :(得分:0)
NSString *theEntireString = @"afsfaof";
NSRange textRange = [[theEntireString lowercaseString] rangeOfString:@"long"];
if (textRange.length < 10) {
NSRange finalRange = NSMakeRange((10-textRange.length)/2, 10);
}else{
NSString *subString = [theEntireString substringWithRange:textRange];
}