如何为每个字的第一字符,或者整个字符串的第一个字符,用C#? [英] How to capitalize the first character of each word, or the first character of a whole string, with C#?

查看:194
本文介绍了如何为每个字的第一字符,或者整个字符串的第一个字符,用C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以写我自己的算法来做到这一点,但我觉得应该是等同于<一个href=\"http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001339\">ruby's在C#人性化。

I could write my own algorithm to do it, but I feel there should be the equivalent to ruby's humanize in C#.

我GOOGLE了它,但只有找到了人性化的日期。

I googled it but only found ways to humanize dates.

例如:


  • 打开排版Lipsum ET外星人分成的方式排版lipsum等

  • 打开排版lipsum等到排版Lipsum ET外星人
  • 系统方法

推荐答案

由于在<一个意见讨论href=\"http://stackoverflow.com/questions/913090/how-to-capitalize-the-first-character-of-each-word-or-the-first-character-of-a-w/913102#913102\">@miguel's回答,你可以使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx\"><$c$c>TextInfo.ToTitleCase因为.NET 1.1这已经可用。下面是对应于你的榜样一些code:

As discussed in the comments of @miguel's answer, you can use TextInfo.ToTitleCase which has been available since .NET 1.1. Here is some code corresponding to your example:

string lipsum1 = "Lorem lipsum et";

// Creates a TextInfo based on the "en-US" culture.
TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;

// Changes a string to titlecase.
Console.WriteLine("\"{0}\" to titlecase: {1}", 
                  lipsum1, 
                  textInfo.ToTitleCase( lipsum1 )); 

// Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et

这会忽略外壳东西都是全部大写,如LOREM LIPSUM ET,因为它走的情况下,如果照顾缩略语在文本(使的 NAMBLA 不会成为NAMBLA或NAMBLA)。

It will ignore casing things that are all caps such as "LOREM LIPSUM ET" because it is taking care of cases if acronyms are in text (so that "NAMBLA" won't become "nambla" or "Nambla").

不过,如果你只是想利用的第一个字符,你可以做的解决方案,在<一个href=\"http://channel9.msdn.com/forums/TechOff/252814-Howto-Capitalize-first-char-of-words-in-a-string-NETC/\">here…或者你可以只拆分字符串并利用该列表中的第一个:

However if you only want to capitalize the first character you can do the solution that is over here… or you could just split the string and capitalize the first one in the list:

string lipsum2 = "Lorem Lipsum Et";

string lipsum2lower = textInfo.ToLower(lipsum1);

string[] lipsum2split = lipsum2lower.Split(' ');

bool first = true;

foreach (string s in lipsum2split)
{
    if (first)
    {
        Console.Write("{0} ", textInfo.ToTitleCase(s));
        first = false;
    }
    else
    {
        Console.Write("{0} ", s);
    }
}

// Will output: Lorem lipsum et

这篇关于如何为每个字的第一字符,或者整个字符串的第一个字符,用C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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