Map char to int in Objective-C
I have a need to map char
values to int
values in Objective-C. I know NSDictionary is out because it deals with reference types, and these are values. The map will be used while iterating through an NSString. Each character in the string will be converted to an integer value. All the integers will be summed together.
Using NSDictionary seems like a bad fit because of all the type coercion I'd have to do. (Converting values types, char and int, to reference types.)
I figure I'll have to drop down to C to do this, but my experience with C libraries is very limited.
Is there something most C developers use that will map char
values to int
values?
Edit for clarification
The C# equivalent would be a Dictionary<char,int>
.
In pseudocode, I'd like to the following:
for (int i = 0; i < [string length]; i++) {
char current = [string characterAtIndex:i];
int score = map[current]; // <- I want 开发者_开发百科map without boxing
// do something with score
}
Char to int?
char aChar = 'a';
int foo = (int) aChar;
Done. No need for a hash or anything else. Even if you wanted to map char -> NSNumber, an array of 256 char's (char being a signed 8 bit type) is very little overhead.
(Unless I entirely misparsed your question -- are you asking for (char*)? ... i.e. C strings? Show some code.).
If I understand correctly, you want to store char
s and int
s in a dictionary, as keys and values. However, NSDictionary only accepts objects. The solution? Wrap the char
s and int
s in the NSNumber
object:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:1],
[NSNumber numberWithChar:'a'],
[NSNumber numberWithInt:2],
[NSNumber numberWithChar:'b'],
nil];
Or if you don't want boxing, why not just make a function that takes char
s and returns int
s?
int charToScore(char character)
{
switch (character) {
case 'a':
return 1;
case 'b':
return 2;
default:
return 0;
}
}
@Pontus has the correct answer in Objective-C, but if you're willing to use C++, you can use std::map<char, int>
(or the still-slightly-nonstandard unordered_map<char, int>
.)
To use C++ from within Objective-C, you must rename the file from Whatever.m
to Whatever.mm
--this tells GCC that the file contains Objective-C++, which allows you to use the Objective-C syntax with C++ underpinnings.
精彩评论