Objective c 是否将NSString中的第一个数字转换为整数?
我有这样一个字符串:Objective c 是否将NSString中的第一个数字转换为整数?,objective-c,cocoa,cocoa-touch,nsstring,Objective C,Cocoa,Cocoa Touch,Nsstring,我有这样一个字符串: @"200hello" 或 我希望能够做的是获取NSString中第一个出现的数字,并将其转换为int 因此,"200hello"将变成int=200 并且@“0something”将变成int=0。我可能会使用正则表达式(用stellar实现)。那就有点像: #import "RegexKitLite.h" NSString * original = @"foo 220hello"; NSString * number = [original stringByMatch
@"200hello"
或
我希望能够做的是获取NSString中第一个出现的数字,并将其转换为int
因此,"200hello"将变成int=200
并且@“0something”将变成int=0。我可能会使用正则表达式(用stellar实现)。那就有点像:
#import "RegexKitLite.h"
NSString * original = @"foo 220hello";
NSString * number = [original stringByMatching:@"[^\\d]*(\\d+)" capture:1];
return [number integerValue];
regex@“[^\d]*(\d+”表示“后跟至少一个数字字符的任意数量的非数字字符”
如果号码不总是在开头:
NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
int value = [[@"adfsdg1000safkaj" stringByTrimmingCharactersInSet:nonDigits] intValue];
如果int值始终位于字符串的开头,则可以简单地使用intValue
NSString *string = @"123hello";
int myInt = [string intValue];
Steve Ciarcia曾经说过,一个测量结果胜过一百个工程师的意见。第一个也是最后一个“如何从NSString中获取int值”开始了
以下是竞争者:(使用(x=0;x='0')&(c的难以置信的高精度,每次比赛占用的微秒数和使用的字节数)我想出了自己的答案,可能比提供的其他答案更快、更容易 我的回答是假设你知道数字的开始和结束位置
NSString *myString = @"21sss";
int numberAtStart = [[myString substringToIndex:2] intValue];
你也可以通过另一种方式开始工作:
NSString *myString = @"sss22";
int numberAtEnd = [[myString substringFromIndex:3] intValue];
仅当数字是字符串的第一部分时,此选项才有效。诚然,示例似乎暗示了这一点,但即使数字前面有字母,我的答案也会有效。您的答案不会有效。=)对于之前和之后的角色,这是一个很好的解决方法。我不知道NSCharacterSet上的-invertedSet方法。+1现在我对否决你的答案感到很难过。你总是可以“取消否决投票”他的回答是再次点击向下箭头。好的,取消向下投票,你说服了我。但是当人们在iPhone电池电量不足的情况下开始建造核电站时,不要抱怨。我不会向下投票,因为你的项目中可能有RegexKitLite,但出于我的目的,是的,这有点太多了。无论如何,谢谢+1这里没有否决票,但我同意NSScanner是一种更干净的方法。特别是因为你必须为不同的数字类型编写一个新的正则表达式,在NSScanner中,你可以切换到scanFloat:或scanDouble:等@Quinn当我看到这个问题时,我也立即想到了NSScanner。在阅读答案之前是。-)同样,就像@Nikiolai Ruhe的答案一样,只有在数字前没有字母时,这才有效。可能是这样,但问题是“第一个出现的数字”,这意味着前面可能有字母是的,但是询问者的例子总是在开头显示数字。从技术上讲,提问者混淆了“int”和“Integer”,因此他可能还想使用-[NSString integerValue]来代替。哇,非常感谢您为衡量性能所做的努力+1或者您可以使用我刚才添加的我自己的答案的结果进行更新。另外,请添加您为执行基准测试而编写的代码。
characterSet time: 1.36803us 12.5 / 1.00 memory: 64 bytes (via Nikolai Ruhe)
original RKL time: 1.20686us 11.0 / 0.88 memory: 16 bytes (via Dave DeLong)
modified RKL time: 1.07631us 9.9 / 0.78 memory: 16 bytes (me, changed regex to \d+)
scannerScanInt time: 0.49951us 4.6 / 0.36 memory: 32 bytes (via Nikolai Ruhe)
intValue time: 0.16739us 1.5 / 0.12 memory: 0 bytes (via zpasternack)
rklIntValue time: 0.10925us 1.0 / 0.08 memory: 0 bytes (me, modified RKL example)
characterSet time: 1.36803us 12.5 / 1.00 memory: 64 bytes (via Nikolai Ruhe)
original RKL time: 0.58446us 5.3 / 0.43 memory: 16 bytes (via Dave DeLong)
modified RKL time: 0.54628us 5.0 / 0.40 memory: 16 bytes (me, changed regex to \d+)
scannerScanInt time: 0.49951us 4.6 / 0.36 memory: 32 bytes (via Nikolai Ruhe)
intValue time: 0.16739us 1.5 / 0.12 memory: 0 bytes (via zpasternack)
rklIntValue time: 0.10925us 1.0 / 0.08 memory: 0 bytes (me, modified RKL example)
original RKL time: 0.51188us 4.7 / 0.37 memory: 16 bytes using intValue
modified RKL time: 0.47665us 4.4 / 0.35 memory: 16 bytes using intValue
original RKL time: 0.44337us 4.1 / 0.32 memory: 16 bytes using rklIntValue
modified RKL time: 0.42128us 3.9 / 0.31 memory: 16 bytes using rklIntValue
shell% gcc -DNS_BLOCK_ASSERTIONS -mdynamic-no-pic -std=gnu99 -O -o stackOverflow stackOverflow.m RegexKitLite.m -framework Foundation -licucore -lauto
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdint.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <objc/objc-auto.h>
#include <malloc/malloc.h>
#import <Foundation/Foundation.h>
#import "RegexKitLite.h"
static double cpuTimeUsed(void);
static double cpuTimeUsed(void) {
struct rusage currentRusage;
getrusage(RUSAGE_SELF, ¤tRusage);
double userCPUTime = ((((double)currentRusage.ru_utime.tv_sec) * 1000000.0) + ((double)currentRusage.ru_utime.tv_usec)) / 1000000.0;
double systemCPUTime = ((((double)currentRusage.ru_stime.tv_sec) * 1000000.0) + ((double)currentRusage.ru_stime.tv_usec)) / 1000000.0;
double CPUTime = userCPUTime + systemCPUTime;
return(CPUTime);
}
@interface NSString (IntConversion)
-(int)rklIntValue;
@end
@implementation NSString (IntConversion)
-(int)rklIntValue
{
CFStringRef cfSelf = (CFStringRef)self;
UInt8 buffer[64];
const char *cptr, *optr;
char c;
if((cptr = optr = CFStringGetCStringPtr(cfSelf, kCFStringEncodingMacRoman)) == NULL) {
CFRange range = CFRangeMake(0L, CFStringGetLength(cfSelf));
CFIndex usedBytes = 0L;
CFStringGetBytes(cfSelf, range, kCFStringEncodingUTF8, '?', false, buffer, 60L, &usedBytes);
buffer[usedBytes] = 0U;
cptr = optr = (const char *)buffer;
}
while(((cptr - optr) < 60) && (!((((c = *cptr) >= '0') && (c <= '9')) || (c == '-') || (c == '+'))) ) { cptr++; }
return((int)strtoimax(cptr, NULL, 0));
}
@end
int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused))) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
#ifdef __OBJC_GC__
objc_start_collector_thread();
objc_clear_stack(OBJC_CLEAR_RESIDENT_STACK);
objc_collect(OBJC_EXHAUSTIVE_COLLECTION | OBJC_WAIT_UNTIL_DONE);
#endif
BOOL gcEnabled = ([objc_getClass("NSGarbageCollector") defaultCollector] != NULL) ? YES : NO;
NSLog(@"Garbage Collection is: %@", gcEnabled ? @"ON" : @"OFF");
NSLog(@"Architecture: %@", (sizeof(void *) == 4UL) ? @"32-bit" : @"64-bit");
double startTime = 0.0, csTime = 0.0, reTime = 0.0, re2Time = 0.0, ivTime = 0.0, scTime = 0.0, rklTime = 0.0;
NSString *valueString = @"foo 2020hello", *value2String = @"2020hello";
NSString *reRegex = @"[^\\p{DecimalNumber}]*(\\d+)", *re2Regex = @"\\d+";
int value = 0;
NSUInteger x = 0UL;
{
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *nonDigits = [digits invertedSet];
NSScanner *scanner = [NSScanner scannerWithString:value2String];
NSString *csIntString = [valueString stringByTrimmingCharactersInSet:nonDigits];
NSString *reString = [valueString stringByMatching:reRegex capture:1L];
NSString *re2String = [valueString stringByMatching:re2Regex];
[scanner scanInt:&value];
NSLog(@"digits : %p, size: %lu", digits, malloc_size(digits));
NSLog(@"nonDigits : %p, size: %lu", nonDigits, malloc_size(nonDigits));
NSLog(@"scanner : %p, size: %lu, int: %d", scanner, malloc_size(scanner), value);
NSLog(@"csIntString : %p, size: %lu, '%@' int: %d", csIntString, malloc_size(csIntString), csIntString, [csIntString intValue]);
NSLog(@"reString : %p, size: %lu, '%@' int: %d", reString, malloc_size(reString), reString, [reString intValue]);
NSLog(@"re2String : %p, size: %lu, '%@' int: %d", re2String, malloc_size(re2String), re2String, [re2String intValue]);
NSLog(@"intValue : %d", [value2String intValue]);
NSLog(@"rklIntValue : %d", [valueString rklIntValue]);
}
for(x = 0UL, startTime = cpuTimeUsed(); x < 100000UL; x++) { value = [[valueString stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] intValue]; } csTime = (cpuTimeUsed() - startTime) / (double)x;
for(x = 0UL, startTime = cpuTimeUsed(); x < 100000UL; x++) { value = [[valueString stringByMatching:reRegex capture:1L] intValue]; } reTime = (cpuTimeUsed() - startTime) / (double)x;
for(x = 0UL, startTime = cpuTimeUsed(); x < 100000UL; x++) { value = [[valueString stringByMatching:re2Regex] intValue]; } re2Time = (cpuTimeUsed() - startTime) / (double)x;
for(x = 0UL, startTime = cpuTimeUsed(); x < 100000UL; x++) { value = [valueString rklIntValue]; } rklTime = (cpuTimeUsed() - startTime) / (double)x;
for(x = 0UL, startTime = cpuTimeUsed(); x < 100000UL; x++) { value = [value2String intValue]; } ivTime = (cpuTimeUsed() - startTime) / (double)x;
for(x = 0UL, startTime = cpuTimeUsed(); x < 100000UL; x++) { [[NSScanner scannerWithString:value2String] scanInt:&value]; } scTime = (cpuTimeUsed() - startTime) / (double)x;
NSLog(@"csTime : %.5lfus", csTime * 1000000.0);
NSLog(@"reTime : %.5lfus", reTime * 1000000.0);
NSLog(@"re2Time: %.5lfus", re2Time * 1000000.0);
NSLog(@"scTime : %.5lfus", scTime * 1000000.0);
NSLog(@"ivTime : %.5lfus", ivTime * 1000000.0);
NSLog(@"rklTime: %.5lfus", rklTime * 1000000.0);
[NSString clearStringCache];
[pool release]; pool = NULL;
return(0);
}
NSString *myString = @"21sss";
int numberAtStart = [[myString substringToIndex:2] intValue];
NSString *myString = @"sss22";
int numberAtEnd = [[myString substringFromIndex:3] intValue];
int i;
NSString* string;
i = [string intValue];