Làm thế nào để chuyển đổi một chuỗi thành chuỗi có ký tự đầu viết hoa? (How to convert a string to title case/proper case in CSharp?)





Bài viết này sẽ hướng dẫn cách sử dụng lớp CultureInfo và TextInfo để chuyển đổi một chuỗi thành một chuỗi mới với các ký tự đầu được viết hoa(title case or proper case). Về 2 lớp trên trong bài này bạn hãy tạm hiểu là lớp hỗ trợ cung cấp các method và property để thực hiện việc chuyển đổi.






Dưới đây là mã(code) để thực hiện việc chuyển đối, à ngoài ra hai lớp CultureInfo và TextInfo cũng hỗ trợ convert thành chữ hoa và chữ thường, trong ví dụ bên dưới tôi cũng giới thiệu kèm theo.

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

namespace HowToPropeCaseString
{
    class Program
    {
        static void Main(string[] args)
        {
            string str01 = "Welcom to my site.";

            //Get the culture property of the thread.
            CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
            //Create TextInfo object.
            TextInfo textInfo = cultureInfo.TextInfo;

            //Convert to uppercase.
            Console.WriteLine("Upper Case: " + textInfo.ToUpper(str01));
            //Convert to lowercase.
            Console.WriteLine("Lower Case: " + textInfo.ToLower(str01));
            //Convert to title case.
            Console.WriteLine("Proper Case: " + textInfo.ToTitleCase(str01));

            Console.ReadLine();

        }
    }
}

Kết quả sau khi ứng dụng được thực thi sẽ là.

























No comments:

Post a Comment