问题
如果要在大小写之间转换,如何提高速度?
思路
让我们观察大小写字母的ASCII码:
大写字母 | ASCII_DEC | ASCII_BIN | ASCII_BIN | ASCII_DEC | 小写字母 |
---|---|---|---|---|---|
A | 65 | 01 0 00001 | 01 1 00001 | 97 | a |
B | 66 | 01 0 00010 | 01 1 00010 | 98 | b |
… | … | … | … | … | … |
Z | 90 | 01 0 11010 | 01 1 11010 | 122 | z |
测试代码
#include <stdio.h>
#include <stdlib.h>
void A2a(char * C) {
for (int i = 0; C[i] != ‘\0‘; i++) C[i] |= 32; // 0100000
}
void a2A(char * C) {
for (int i = 0; C[i] != ‘\0‘; i++) C[i] &= 95; // 1011111
}
void a2A_A2a(char * C) {
for (int i = 0; C[i] != ‘\0‘; i++) C[i] ^= 32; // 0100000
}
int main() {
char C1[98] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char C2[98] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char C3[98] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
printf("A2a:\n");
printf("Before: %s\n\n", C1);
A2a(C1);
printf("After : %s\n\n", C1);
printf("------------------------------------------------------------\n\n");
printf("a2A:\n");
printf("Before: %s\n\n", C2);
a2A(C2);
printf("After : %s\n\n", C2);
printf("-------------------------------------------------------------\n\n");
printf("a2A_A2a:\n");
printf("Before: %s\n\n", C3);
a2A_A2a(C3);
printf("After : %s\n\n", C3);
system("pause");
return 0;
}
测试结果
弊端
注意这里只能在字母之间转换,当文本含有其他字符的时候,会将“无辜”的字符变成奇奇怪怪的字符。
原文地址:http://blog.csdn.net/u012925008/article/details/45505465