Python中使用字符的ascii码计算
输入一个字符串,统计其中每个字符出现的次数,之前使用的是构造一个含有26个字母的字典,初始每个字母对应的键值都是0,遍历字符串,没获得一个字符将字典中对应键值加一,代码冗长
其实可以直接使用一个列表来实现。asc码中’b’字符和’a’字符差为1,而正好列表中下标为1的项表示’b’出现的次数那么我们可以使用ord函数获得字符的asc码,并使用asc码的差值作为列表下标。
例如:
test=input()#输入字符串
count=[0 for i in range(26)]#初始化count
for i in range(len(test)):
count[ord(test[i])-ord('a')]+=1#遍历字符串
print(count)
输入:
abcdef
输出:
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Java中使用Unicode码
Unicode采用无符号编码我们可以把java的字符作为整数对待例如:
package helloworld;
public class helloworld{
public static void main(String[] args) {
char word1='a',word2='@';
int p1=23045,p2=45213;
System.out.println("d 在Unicode表中的位置是"+(int)word1);
System.out.println("@在Unicode表中的位置是"+(int)word2);
System.out.println("23054在Unicode表中代表"+(char)p1);
System.out.println("45213在Unicode表中代表"+(char)p2);
}
}
输出:
d 在Unicode表中的位置是97
@在Unicode表中的位置是64
23054在Unicode表中代表娅
45213在Unicode表中代表낝