是否可以在Xamarin.Forms中将字符串转换为Title Case? [英] Is it possible to Convert a string to Title Case in Xamarin.Forms?

查看:72
本文介绍了是否可以在Xamarin.Forms中将字符串转换为Title Case?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在我的程序中,我有一个Entry像这样:

So in my program I have an Entry like so:

<Entry Text="{Binding testText}"/>

这是绑定到属性的.

我找到了这个系统. Xamarin UWP 库中的Globalization.TextInfo.ToTitleCase ,但我正在寻找适用于所有平台的通用解决方案

I have found this System.Globalization.TextInfo.ToTitleCase in the Xamarin UWP library, but I am looking for a generic solution for all platforms

有没有可以应用到我的字符串的算法,以便在更改字符串时将标题大小写应用于字符串?

Is there an algorithm I can apply to my string to apply Title Case to the string when it is changed?

推荐答案

我在以下链接上找到了很好的解决方案:

I find a good solution on the following link:

https://www.codeproject .com/Tips/1004964/Title-Case-in-VB-net-or-Csharp

此解决方案要注意首字母大写和转义词,例如, 一个,在

this solution take care about first-letter-capital and escape words such as the, a, in

public static class StringExtensions
    {
        public static string ToTitleCase(this string s)
        {

        var upperCase = s.ToUpper();
        var words = upperCase.Split(' ');

        var minorWords = new String[] {"ON", "IN", "AT", "OFF", "WITH", "TO", "AS", "BY",//prepositions
                                   "THE", "A", "OTHER", "ANOTHER",//articles
                                   "AND", "BUT", "ALSO", "ELSE", "FOR", "IF"};//conjunctions

        var acronyms = new String[] {"UK", "USA", "US",//countries
                                   "BBC",//TV stations
                                   "TV"};//others

        //The first word.
        //The first letter of the first word is always capital.
        if (acronyms.Contains(words[0]))
        {
            words[0] = words[0].ToUpper();
        }
        else
        {
            words[0] = words[0].ToPascalCase();
        }

        //The rest words.
        for (int i = 0; i < words.Length; i++)
        {
            if (minorWords.Contains(words[i]))
            {
                words[i] = words[i].ToLower();
            }
            else if (acronyms.Contains(words[i]))
            {
                words[i] = words[i].ToUpper();
            }
            else
            {
                words[i] = words[i].ToPascalCase();
            }
        }

        return string.Join(" ", words);

    }

    public static string ToPascalCase(this string s)
    {
        if (!string.IsNullOrEmpty(s))
        {
            return s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower();
        }
        else
        {
            return String.Empty;
        }
    }
}

这篇关于是否可以在Xamarin.Forms中将字符串转换为Title Case?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆