Reputation: 135
I am learning about arrays and data types in C. My question is that how can I compute the sum of the chars of a string. The value of chars in POINTS array for example the value of A(or a) is 1 and B(or b) is 3 etc. Now my question is that how can tell my program that A is 1 because by default it is working with the asci table. I will be happy for your help.
#include <stdio.h>
#include <string.h>
// Points assigned to each letter of the alphabet
int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
/////////////// A B C D . . .
int compute_score(string word);
int main(void)
{
int score = compute_sum(Amazing!);
//it must calculates 1 + 1 + 1 + 10 + 1 + 1 + 2 + 0
}
int compute_sum(string word)
{
for(int i=0 ; i<strlen(word);i++)
{
//todo
}
}
Upvotes: 0
Views: 1067
Reputation: 1835
Generally speaking I would probably do something like this:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
static const int points[UINT8_MAX + 1] = {
['a'] = 1,
['b'] = 3,
['c'] = 3,
['d'] = 2,
['e'] = 1,
['f'] = 4,
['g'] = 2,
['h'] = 4,
['i'] = 1,
['j'] = 8,
['k'] = 5,
['l'] = 1,
['m'] = 3,
['n'] = 1,
['o'] = 1,
['p'] = 3,
['q'] = 10,
['r'] = 1,
['s'] = 1,
['t'] = 1,
['u'] = 1,
['v'] = 4,
['w'] = 4,
['x'] = 8,
['y'] = 4,
['z'] = 10,
};
static int compute_sum(const char *word)
{
const unsigned char *c;
int sum = 0;
for (c = (const unsigned char *) word; *c; c++)
sum += points[(int) *c];
return sum;
}
int main(void)
{
int score;
score = compute_sum("Amazing!");
printf("Score: %d\n", score);
}
Rationale: more readable, less error prone, no arithmetic needed, less chance of UB.
Upvotes: 3
Reputation: 780889
In ASCII and all character encodings derived from it (including Unicode) the letters in the Latin alphabet are all contiguous. So you can subtract the encoding of A
or a
from a letter to get its corresponding index.
int compute_sum(string word)
{
int total = 0;
for(int i=0 ; i<strlen(word);i++)
{
if (isupper(word[i])) {
total += POINTS[word[i] - 'A'];
} else if (islower(word[i])) {
total += POINTS[word[i] - 'a'];
}
}
return total;
}
Upvotes: 2