好吧,我必须做一个任务,以独特的方式对数组元素进行排序。
因此,例如,如果我输入第一个字符串:BOB,我必须这样做:2+15+2(因为它们在字母表中的位置)然后除以字符数 /3 并对所有输入的字符串执行此操作,然后按从高到低对它们进行排序。:)
我的问题是,我如何为 A、B、C、D、E 设置值 1、2、3、4、5 ......(仅限大字母)。
谢谢你。
你需要定义一个函数
int weight(const std::string& s);
然后通过 char 迭代字符串 char 并执行以下操作:
w = ch - 'A' + 1
您还可以检查字符是否在“A”和“Z”之前或假设。
您需要阅读有关ASCII的更多信息
编辑: 权重函数代码(简化):
int weight(const std::string& s) {
int sum = 0, i = 0;
for(i = 0; i < s.size(); i++) {
char ch = s[i];
sum += ch - 'A' + 1;
}
return sum/i;
}
如果您正在使用 ASCII 机器,@StoryTeller 的答案有效。否则,您可以创建一个数组以在两者之间进行映射:
const char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const int numbers [ 256 ] = { 0 };
for ( size_t index = 0; index < sizeof letters; ++index ) {
numbers [ letters [ index ] ] = index + 1;
}
assert ( numbers [ 'A' ] == 1 )
assert ( numbers [ 'Z' ] == 26 )
要获取值,您可以使用以下代码:
int getValue(char which)
{
int ret = 0;
switch(which)
{
case 'a' : ret = 1 ; break;
case 'A' : ret = 27 ; break;
case 'b' : ret = 2 ; break;
case 'B' : ret = 28 ; break;
// and so on....
}
return ret;
}
int result = 0;
while(....)
{
result = result + getValue(myarray[counter]);
}
您只需要将字符串转义到数组并循环遍历它...