例:2=ABC, 3=DEF, 4=GHI, 5=JKL,
6=MNO, 7=PRS, 8=TUV, 9=WXY
輸入 A-BDG-WWX
則輸出 2-234-999
#include <stdio.h>
#define STRLEN 20
int main(void) {
char conv[25]={
'2','2','2',
'3','3','3',
'4','4','4',
'5','5','5',
'6','6','6',
'7','7','7','7',
'8','8','8',
'9','9','9'
};
char str[STRLEN];
fgets(str, sizeof(str), stdin);
int i=0;
while ((i<STRLEN)&&(str[i] != '\n')) {
if ((str[i] >= 'A')&&(str[i] <= 'Y')&&(str[i] != 'Q')) {
printf("%c", conv[str[i]-'A']);
} else {
printf("%c", str[i]);
}
i++;
}
return 0;
}
不做防呆,簡單用Python
#!/usr/bin/env python3
alphanum = {'A': '2', 'B': '2', 'C': '2',
'D': '3', 'E': '3', 'F': '3',
'G': '4', 'H': '4', 'I': '4',
'J': '5', 'K': '5', 'L': '5',
'M': '6', 'N': '6', 'O': '6',
'P': '7', 'R': '7', 'S': '7',
'T': '8', 'U': '8', 'V': '8',
'W': '9', 'X': '9', 'Y': '9'
}
def tran(x):
if x == '-':
return x
else:
return alphanum[x]
lst = 'A-BDG-WWX'
print(lst)
print( ''.join(list(map(tran, lst))))
result:
|=> ./dictmap1.py
A-BDG-WWX
2-234-999
單純考慮資料擴充的方便性,用 map + array的寫法 (Javascript)
演算法可以再優化
let digitalCharMap = {
'-': ['-'],
'2': ['A', 'B', 'C'],
'3': ['D', 'E', 'F'],
'4': ['G', 'H', 'I'],
'5': ['J', 'K', 'L'],
'6': ['M', 'N', 'O'],
'7': ['P', 'R', 'S'],
'8': ['T', 'U', 'V'],
'9': ['W', 'X', 'Y']
}
function getIntOfString (inputString) {
let result = ''
for (let singleChar of inputString ) {
let isExists = false
for (let numKey in digitalCharMap) {
if (digitalCharMap[numKey].indexOf(singleChar) >= 0) {
result += numKey
isExists = true
}
}
if (isExists !== true) {
return `${singleChar} is not exists`
}
}
return result
}
console.log(getIntOfString('ADA-B'))
//output: "232-2"
console.log(getIntOfString('ADZ-B'))
//output: "Z is not exists"