关于定制NSString

时间:2012-10-03 13:50:35

标签: ios nsstring substring

我有很多字符串,例如3:

1. example old
14. example new
234. example 45

我想排除第一个数字并将其设为:

example old
example new
example 45

我的工作是:

   NSString *fixed1 = [str substringWithRange:NSMakeRange(3, [str length]-3)];
   NSString *fixedStr = [fixed1 stringByReplacingOccurrencesOfString:@". " withString:@""];

我得到的是:

example old
 example new
example 45

问题是“示例新”开头的空间。如果我试试这个,我不知道如何删除它:

 NSString *fixed1 = [str substringWithRange:NSMakeRange(3, [str length]-3)];
 NSString *fixed2 = [fixed1 stringByReplacingOccurrencesOfString:@". " withString:@""];
 NSString *fixedStr = [fixed2 stringByReplacingOccurrencesOfString:@" " withString:@""];

我明白了:

exampleold
examplenew
example45

我为此疯狂,请有人有一个很好的&简单的想法如何解决?

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用

- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set

[NSCharacterSet whitespaceCharacterSet]作为参数来削减开头和结尾的空格。

答案 1 :(得分:2)

- (NSString *) customizeString:(NSString *)input {
    NSArray *components = [input componentsSepratedByString:@". "];
    return [components objectAtIndex:1];
}

如果您的字符串格式与您在问题中指定的格式相同,则此函数效果很好。但是将代码放在try{...}catch(){}块中以防止任何异常。这只是一个简单的解决方案,但不能解决。