字符串首字母大小写转换

作者:追风剑情 发布于:2018-11-28 20:04 分类:C#

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test3
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[]{
                "aaa","bbb","ccc","ddd","eee","fff","ggg"
            };

            Console.WriteLine("首字母大写:");
            for (int i = 0; i < arr.Length; i++) {
                arr[i] = FirstToUpper(arr[i]);
            }
            Print(arr);

            Console.WriteLine("首字母小写:");
            for (int i = 0; i < arr.Length; i++) {
                arr[i] = FirstToLower(arr[i]);
            }
            Print(arr);
            Console.Read();
        }

        // 首字母大写
        protected static string FirstToUpper(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);
        }

        // 首字母小写
        protected static string FirstToLower(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);
        }

        private static void Print(string[] arr)
        {
            bool first = true;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < arr.Length; i++)
            {
                if (!first)
                    sb.Append(",");
                sb.Append(arr[i]);
                first = false;
            }
            Console.WriteLine(sb.ToString());
        }
    }
}

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号