Transforming a NSString @"123" in an (short)array[] = {1, 2, 3}?
I can't imagine a "clean" or efficient method of doing this.
I would like to transform a string of numbers like @"1234" into an array of shorts for a calculator pet project*.
I think of getting substrings and then the intValue of the substring but it sounds cumbersome and overkill. Would there be a more elegant way of doing it?
Thanks in advance!
* I know that there are more efficient ways to do maths and plenty of C libraries do this but it's for m开发者_StackOverflow社区y own education :-).
If I have this straight, you want to turn an NSString into a short array? This function assumes each character in the NSString is a separate short. Oh, and don't forget to free that array when you're done with it!
//Stephen Melvin <jinksys@gmail.com>
short *NSStringToShortArray(NSString *digits){
int count = [digits length];
short *shortArray = malloc(sizeof(short)*count);
for(int i = 0; i<count; i++){
shortArray[i] = (short)[digits characterAtIndex:i] - '0';
}
return shortArray;
}
A good calculator interface should take one string of characters as a single number then after the operation is selected it clears the field to accept the next number.
For example.
You type in 2 then hit the * button, the field clears and you type in 2 again and press = and get 4.
If you want the interface to accept an equation or a script then you should read up on parsing numeric equations.
精彩评论