开发者

Objective-c convert NSString into NSInteger

I've got this little problem. When I have a string "3 568 030" and I use [myString intValue]; it gives me result just 3, the problem is I want to convert the whole numb开发者_StackOverflow社区er into int/nsinteger. The string always contains just the number if that's any help. I tried using replaceoccurencesofstring (or what is the name) and it somehow didn't work...

Thanks


Do:

NSString *str = @"3 568 030";

int aValue = [[str stringByReplacingOccurrencesOfString:@" " withString:@""] intValue];
NSLog(@"%d", aValue);

output

3568030


That is because of the spaces on your string you will have to remove the whitespaces first like this:

NSString *trimmedString = [myString stringByReplacingOccurrencesOfString:@" " withString:@""];

NSInteger *value = [trimmedString intValue];


My guess is that you're using stringByReplacingOccurencesOfString:: wrongly.

//Remove spaces.
myString = [myString stringByReplacingOccurencesOfString:@" " withString @""];
int myNumber = [myString intValue];


First, remove all the whitespaces in your original string using :

NSString *trimmedString = [yourOriginalString stringByTrimmingCharactersInSet:
                              [NSCharacterSet whitespaceAndNewlineCharacterSet]];

Then, you can convert it to an int/NSInteger. beware: using [myString intValue] will cast your string to an int, but [myString integerValue] will cast it to a NSInteger.


NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:@"42"];
[f release];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜