objective C中简洁的字符串切片

2024-09-29 21:57:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在Objective-C中有没有一种简洁的方法来切分字符串?到目前为止,我有:

f = [f stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""];

这不像Python的好:

^{pr2}$

如果不得不做一些类似f[1:4]的事情,那就更粗糙了:

f = [f stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""];
f = [f stringByPaddingToLength:(4-1) withString:@"" startingAtIndex:0];

Tags: 方法字符串事情objectivepr2withstringnsmakerangestartingatindex
2条回答

您可能正在寻找以下方法:

- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;

例如,f = f[1:]变成:

^{pr2}$

并且f = f[1:4]变成:

f = [f substringWithRange:NSMakeRange(1,3)];

只需小心索引和范围不超出边界,否则将抛出NSRangeException!在

尝试substringWithRange:。例如

[s substringWithRange:NSMakeRange(1, s.length - 1)]

或者

^{pr2}$

相关问题 更多 >

    热门问题