C# 英文字母转换大小写

例子:将输入的英文单词首字母设置为大写,代码如下:

    public string TitleToUpper( string str)
    {
        if (string.IsNullOrEmpty(str))
            return string.Empty;

        char[] s = str.ToCharArray();
        char c = s[0];

        if ('a' <= c && c <= 'z')
            c = (char)(c & ~0x20);

        s[0] = c;

        return new string(s);
    }

原理如下:获取首字母c,比如为‘a’,a在asscii的值为97,和大写的‘A’相差32,所以我们要转换成大写A的原理就是将小写a的二进制数据中表示32的那一位去掉。所以,0x20十六进制代表32,二进制表示为:0010 0000,~0x20为1101 1111,&与计算是遇0为0,所以输入字母&~0x20后,表示32的那一位为0,就相当于减去32.

同理我们想要将小写字母变成大写字母,只需要将32那一位(|)并给输入字符。代码如下:

  public string TitleToLower(string str)
    {
        if (string.IsNullOrEmpty(str))
            return string.Empty;

        char[] s = str.ToCharArray();
        char c = s[0];

        if ('A' <= c && c <= 'Z')
            c = (char)(c | 0x20);

        s[0] = c;

        return new string(s);

    }

 

你可能感兴趣的:(C#)