【问题标题】:Is value of NSString a NSInteger value in iOSNSString 的值是 iOS 中的 NSInteger 值吗
【发布时间】:2014-10-30 10:16:18
【问题描述】:

我很想确定 NSString 中的文本是否为 int 值。

例如:

NSString value = @"something";
int i = value.intValue;
// i -> 0

所以 i 是 0,如果 text 是真正的 int 值,它不会给我信息。

第二个问题是字符串是否相同:

NSString vaue = @"10.10.21.32"
int i = value.intValue;
// i -> 10

如何判断文本是否为真正的int值?

马尔科

【问题讨论】:

    标签: ios xcode nsstring int type-conversion


    【解决方案1】:

    使用NSNumberFormatter,将lenient设置为false,allowsFloats设置为false。

    NSNumberFormatter *intFormat = [NSNumberFormatter alloc] init];
    intFormat.lenient = false;
    intFormat.allowsFloats = false;
    NSNumber *myNumber = [intFormat numberFromString:value];
    int finalValue;
    if (myNumber) { // was able to parse OK
        finalValue = [myNumber intValue];
    } else {
        // handle invalid strings here
    }
    

    【讨论】:

      【解决方案2】:

      我做了一些代码。它将用于识别该字符串是文本、实数或整数。

      #define REGEX_NUMBER @"^[0-9.0-9]*$"
      
      NSString *digitString = @"test";
      
      NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", REGEX_NUMBER];
      
      BOOL isNumber = [phoneTest evaluateWithObject:digitString];
      
      if (isNumber) {
      
          // String contains digit characters
      
          if ([digitString rangeOfString:@"."].location == NSNotFound) {
      
              // String contains real value
              int value = [digitString intValue];
      
          } else {
      
              // String contains int value
              double value = [digitString doubleValue];
      
          }
      } else {
          NSLog(@"alpha-numeric value");
          // String contains alpha-numeric values.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 2011-06-15
        • 1970-01-01
        • 2012-10-19
        • 1970-01-01
        相关资源
        最近更新 更多