【问题标题】:Extracting from the right of a string in objective C [duplicate]从目标C中的字符串右侧提取[重复]
【发布时间】:2013-03-18 06:42:51
【问题描述】:

这似乎是我正在寻找的,但反过来。我希望string 从右侧而不是从左侧提取。 给出从左边提取的例子:

NSString *source = @"0123456789";
NSString *firstFour = [source substringToIndex:4];

Output: "0123"

我正在寻找一个可以从右侧工作的下面的版本(下面的不工作)

NSString *source = @"0123456789";
NSString *lastFour = [source substringToIndex:-4];

Output: "6789"

[source substringFromIndex:6]; 不起作用,因为有时我会得到 000123456789 或 456789 或 6789 的答案。在所有情况下,我只需要字符串中的最后 4 个字符,以便将其转换为数字。

一定有比一堆 if else 语句更好的方法吗?

【问题讨论】:

  • [ source substringFromIndex:source.length - 4 ]
  • this question非常相似。

标签: ios objective-c string text-extraction


【解决方案1】:

由于您不确定字符串的长度,因此您必须在提取之前检查它:

NSString *source = @"0123456789";
NSNumber *number;
if (source.length>=4) {
    NSString *lastFour=[source substringFromIndex:source.length-4];
    number=@([lastFour integerValue]); //and save it in a number, it can be int or NSInteger as per your need
}
NSLog(@"%@",number);

另外,如果您想要一个需要多次调用的快速方法,请创建一个类别:

@implementation NSString (SubstringFromRight)
-(NSString *)substringFromRight:(NSUInteger)from{
    if (self.length<from) {
        return nil;
    }        
    return [self substringFromIndex:self.length-from];
}
@end

并将其用作:NSLog(@"%@",[source1 substringFromRight:4]);

【讨论】:

  • +1,带有异常检查的完整答案。
【解决方案2】:
NSString *source = @"0123456789";
NSString *newString = [source substringFromIndex:[source length] - 4];

NSLog(@"%@",newString);

【讨论】:

    【解决方案3】:

    替换

    NSString *lastFour = [source substringToIndex:-4];
    

    NSString *lastFour = [source substringFromIndex:[source length] - 4];
    

    返回原始字符串 stringlastFour string 的最后 4 个字符。

    【讨论】:

      【解决方案4】:

      您可以使用以下代码从字符串中获取最后 4 个字符。

      NSString *last4Characters = [source substringFromIndex:(source.length - 4)];
      NSLog(@"Last 4 Characters:%@",last4Characters);
      last4Characters=nil;
      

      如果有任何问题请告诉我。

      【讨论】:

        猜你喜欢
        • 2015-11-30
        • 2015-02-20
        • 2011-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-09
        • 1970-01-01
        相关资源
        最近更新 更多