将字符串格式化为标题大小写

发布于 2024-07-04 00:14:06 字数 124 浏览 12 评论 0原文

如何将字符串格式化为标题大小写

How do I format a string to title case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

恋竹姑娘 2024-07-11 00:14:06

下面是一个在 C# 中执行此操作的简单静态方法:

public static string ToTitleCaseInvariant(string targetString)
{
    return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(targetString);
}

Here is a simple static method to do this in C#:

public static string ToTitleCaseInvariant(string targetString)
{
    return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(targetString);
}
满意归宿 2024-07-11 00:14:06

我会谨慎对待自动将所有空格前面的单词转大写,因为这样我可能会冒着招来吹毛求疵者的愤怒的风险。

我至少会考虑为冠词和连词等例外情况实现一个字典。 看哪:

《美女与野兽》

当涉及到专有名词时,事情就变得更加丑陋。

I would be wary of automatically upcasing all whitespace-preceded-words in scenarios where I would run the risk of attracting the fury of nitpickers.

I would at least consider implementing a dictionary for exception cases like articles and conjunctions. Behold:

"Beauty and the Beast"

And when it comes to proper nouns, the thing gets much uglier.

段念尘 2024-07-11 00:14:06

这是一个 Perl 解决方案 http://daringfireball.net/2008/05/title_case

这是一个 Ruby 解决方案http://frankschmitt.org/projects/title-case

这是一个 Ruby 单行解决方案: http://snippets.dzone.com/posts/show/4702

'some string here'.gsub(/\b\w/){
amp;.upcase}

那是什么- liner 正在做的是使用正则表达式将每个单词的第一个字符替换为其大写版本。

Here's a Perl solution http://daringfireball.net/2008/05/title_case

Here's a Ruby solution http://frankschmitt.org/projects/title-case

Here's a Ruby one-liner solution: http://snippets.dzone.com/posts/show/4702

'some string here'.gsub(/\b\w/){
amp;.upcase}

What the one-liner is doing is using a regular expression substitution of the first character of each word with the uppercase version of it.

城歌 2024-07-11 00:14:06

在 Silverlight 中,TextInfo 类中没有 ToTitleCase

这是一种基于正则表达式的简单方法。

注意:Silverlight 没有预编译的正则表达式,但对我来说,这种性能损失不是问题。

    public string TitleCase(string str)
    {
        return Regex.Replace(str, @"\w+", (m) =>
        {
            string tmp = m.Value;
            return char.ToUpper(tmp[0]) + tmp.Substring(1, tmp.Length - 1).ToLower();
        });
    }

In Silverlight there is no ToTitleCase in the TextInfo class.

Here's a simple regex based way.

Note: Silverlight doesn't have precompiled regexes, but for me this performance loss is not an issue.

    public string TitleCase(string str)
    {
        return Regex.Replace(str, @"\w+", (m) =>
        {
            string tmp = m.Value;
            return char.ToUpper(tmp[0]) + tmp.Substring(1, tmp.Length - 1).ToLower();
        });
    }
离旧人 2024-07-11 00:14:06

要在 C 语言中使用它,请使用 ascii 代码 (http://www.asciitable.com/< /a>) 查找 char 的整数值并从中减去 32。


如果您计划接受 az 和 AZ 之外的字符,那么这是一个糟糕的解决方案。

例如:ASCII 134:å,ASCII 143:Å。
使用算术可以得到: ASCII 102: f

使用库调用,不要假设您可以对字符使用整数算术来返回有用的东西。 Unicode 是棘手

To capatilise it in, say, C - use the ascii codes (http://www.asciitable.com/) to find the integer value of the char and subtract 32 from it.

This is a poor solution if you ever plan to accept characters beyond a-z and A-Z.

For instance: ASCII 134: å, ASCII 143: Å.
Using arithmetic gets you: ASCII 102: f

Use library calls, don't assume you can use integer arithmetic on your characters to get back something useful. Unicode is tricky.

我们只是彼此的过ke 2024-07-11 00:14:06

In Perl:

$string =~ s/(\w+)/\u\L$1/g;

这甚至在常见问题解答中也是如此。

In Perl:

$string =~ s/(\w+)/\u\L$1/g;

That's even in the FAQ.

弥繁 2024-07-11 00:14:06

如果您使用的语言具有受支持的方法/函数,则只需使用该方法/函数(如 C# ToTitleCase 方法中所示),

没有,则您需要执行如下操作:

  1. 如果 字符串
  2. 取第一个单词
  3. 该单词的第一个字母大写 1
  4. 向前查找下一个单词
  5. 如果不在字符串末尾则转到 3,否则退出

1 到将其大写,例如 C - 使用 ascii 代码 查找 char 的整数值并从中减去 32它。

代码中需要进行更多的错误检查(确保字母有效等),并且“大写”功能需要对字母施加某种“标题大小写方案”以检查不需要的单词具有能力(“和”、“但是”等。这里是好方案)

If the language you are using has a supported method/function then just use that (as in the C# ToTitleCase method)

If it does not, then you will want to do something like the following:

  1. Read in the string
  2. Take the first word
  3. Capitalize the first letter of that word 1
  4. Go forward and find the next word
  5. Go to 3 if not at the end of the string, otherwise exit

1 To capitalize it in, say, C - use the ascii codes to find the integer value of the char and subtract 32 from it.

There would need to be much more error checking in the code (ensuring valid letters etc.), and the "Capitalize" function will need to impose some sort of "title-case scheme" on the letters to check for words that do not need to be capatilised ('and', 'but' etc. Here is a good scheme)

清风不识月 2024-07-11 00:14:06

类似 Excel 的正确:

public static string ExcelProper(string s) {
    bool upper_needed = true;
    string result = "";
    foreach (char c in s) {
        bool is_letter = Char.IsLetter(c);
        if (is_letter)
            if (upper_needed)
                result += Char.ToUpper(c);
            else
                result += Char.ToLower(c);
        else
            result += c;
        upper_needed = !is_letter;
    }
    return result;
}

Excel-like PROPER:

public static string ExcelProper(string s) {
    bool upper_needed = true;
    string result = "";
    foreach (char c in s) {
        bool is_letter = Char.IsLetter(c);
        if (is_letter)
            if (upper_needed)
                result += Char.ToUpper(c);
            else
                result += Char.ToLower(c);
        else
            result += c;
        upper_needed = !is_letter;
    }
    return result;
}
清泪尽 2024-07-11 00:14:06

用什么语言?

在 PHP 中,它是:

ucwords()

示例:

$HelloWorld = ucwords('hello world');

In what language?

In PHP it is:

ucwords()

example:

$HelloWorld = ucwords('hello world');
梦里人 2024-07-11 00:14:06

在Java中,您可以使用以下代码。

public String titleCase(String str) {
    char[] chars = str.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (i == 0) {
            chars[i] = Character.toUpperCase(chars[i]);
        } else if ((i + 1) < chars.length && chars[i] == ' ') {
            chars[i + 1] = Character.toUpperCase(chars[i + 1]);
        }
    }
    return new String(chars);
}

In Java, you can use the following code.

public String titleCase(String str) {
    char[] chars = str.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (i == 0) {
            chars[i] = Character.toUpperCase(chars[i]);
        } else if ((i + 1) < chars.length && chars[i] == ' ') {
            chars[i + 1] = Character.toUpperCase(chars[i + 1]);
        }
    }
    return new String(chars);
}
z祗昰~ 2024-07-11 00:14:06

我认为使用 CultureInfo 并不总是可靠的,这是手动操作字符串的简单而方便的方法:

string sourceName = txtTextBox.Text.ToLower();
string destinationName = sourceName[0].ToUpper();

for (int i = 0; i < (sourceName.Length - 1); i++) {
  if (sourceName[i + 1] == "")  {
    destinationName += sourceName[i + 1];
  }
  else {
    destinationName += sourceName[i + 1];
  }
}
txtTextBox.Text = desinationName;

I think using the CultureInfo is not always reliable, this the simple and handy way to manipulate string manually:

string sourceName = txtTextBox.Text.ToLower();
string destinationName = sourceName[0].ToUpper();

for (int i = 0; i < (sourceName.Length - 1); i++) {
  if (sourceName[i + 1] == "")  {
    destinationName += sourceName[i + 1];
  }
  else {
    destinationName += sourceName[i + 1];
  }
}
txtTextBox.Text = desinationName;
近箐 2024-07-11 00:14:06

以下是如何执行此操作的简单示例:

public static string ToTitleCaseInvariant(string str)
{
    return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str);
}

Here is a simple example of how to do it :

public static string ToTitleCaseInvariant(string str)
{
    return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str);
}
趁微风不噪 2024-07-11 00:14:06

下面是 Python 中的一个实现: https://launchpad.net/titlecase.py

以及此实现的一个端口我刚刚用 C++ 完成: http://codepad.org/RrfcsZzO

Here's an implementation in Python: https://launchpad.net/titlecase.py

And a port of this implementation that I've just done in C++: http://codepad.org/RrfcsZzO

谷夏 2024-07-11 00:14:06

Excel中有一个内置公式PROPER(n)

很高兴看到我不必自己写!

There is a built-in formula PROPER(n) in Excel.

Was quite pleased to see I didn't have to write it myself!

想你的星星会说话 2024-07-11 00:14:06

http://titlecase.com/ 有一个 API

http://titlecase.com/ has an API

篱下浅笙歌 2024-07-11 00:14:06

在 C# 中

using System.Globalization;  
using System.Threading;  
protected void Page_Load(object sender, EventArgs e)  
{  
  CultureInfo cultureInfo   = Thread.CurrentThread.CurrentCulture;  
  TextInfo textInfo = cultureInfo.TextInfo;  
  Response.Write(textInfo.ToTitleCase("WelcometoHome<br />"));  
  Response.Write(textInfo.ToTitleCase("Welcome to Home"));  
Response.Write(textInfo.ToTitleCase("Welcome@to$home<br/>").Replace("@","").Replace("$", ""));  
}

In C#

using System.Globalization;  
using System.Threading;  
protected void Page_Load(object sender, EventArgs e)  
{  
  CultureInfo cultureInfo   = Thread.CurrentThread.CurrentCulture;  
  TextInfo textInfo = cultureInfo.TextInfo;  
  Response.Write(textInfo.ToTitleCase("WelcometoHome<br />"));  
  Response.Write(textInfo.ToTitleCase("Welcome to Home"));  
Response.Write(textInfo.ToTitleCase("Welcome@to$home<br/>").Replace("@","").Replace("$", ""));  
}
山田美奈子 2024-07-11 00:14:06

在 C# 中,您可以简单地将

CultureInfo.InvariantCulture.TextInfo.ToTitleCase(str.ToLowerInvariant())
  • Invariant
  • Works 与大写字符串一起使用

In C# you can simply use

CultureInfo.InvariantCulture.TextInfo.ToTitleCase(str.ToLowerInvariant())
  • Invariant
  • Works with uppercase strings
死开点丶别碍眼 2024-07-11 00:14:06

不使用现成的函数,一个超级简单的低级算法将字符串转换为标题大小写:


convert first character to uppercase.
for each character in string,
    if the previous character is whitespace,
        convert character to uppercase.

这假设“将字符转换为大写”将正确执行此操作,无论字符是否区分大小写(例如“+”)。

Without using a ready-made function, a super-simple low-level algorithm to convert a string to title case:


convert first character to uppercase.
for each character in string,
    if the previous character is whitespace,
        convert character to uppercase.

This asssumes the "convert character to uppercase" will do that correctly regardless of whether or not the character is case-sensitive (e.g., '+').

他不在意 2024-07-11 00:14:06

这里有一个 C++ 版本。 它有一组不可大写的单词,例如代词和介词。 但是,如果您要处理重要的文本,我不建议自动化此过程。

#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <set>

using namespace std;

typedef vector<pair<string, int> > subDivision;
set<string> nonUpperCaseAble;

subDivision split(string & cadena, string delim = " "){
    subDivision retorno;
    int pos, inic = 0;
    while((pos = cadena.find_first_of(delim, inic)) != cadena.npos){
        if(pos-inic > 0){
            retorno.push_back(make_pair(cadena.substr(inic, pos-inic), inic));
        }
        inic = pos+1;
    }
    if(inic != cadena.length()){
        retorno.push_back(make_pair(cadena.substr(inic, cadena.length() - inic), inic));
    }
    return retorno;
}

string firstUpper (string & pal){
    pal[0] = toupper(pal[0]);
    return pal;
}

int main()
{
    nonUpperCaseAble.insert("the");
    nonUpperCaseAble.insert("of");
    nonUpperCaseAble.insert("in");
    // ...

    string linea, resultado;
    cout << "Type the line you want to convert: " << endl;
    getline(cin, linea);

    subDivision trozos = split(linea);
    for(int i = 0; i < trozos.size(); i++){
        if(trozos[i].second == 0)
        {
            resultado += firstUpper(trozos[i].first);
        }
        else if (linea[trozos[i].second-1] == ' ')
        {
            if(nonUpperCaseAble.find(trozos[i].first) == nonUpperCaseAble.end())
            {
                resultado += " " + firstUpper(trozos[i].first);
            }else{
                resultado += " " + trozos[i].first;
            }
        }
        else
        {
            resultado += trozos[i].first;
        }       
    }

    cout << resultado << endl;
    getchar();
    return 0;
}

Here you have a C++ version. It's got a set of non uppercaseable words like prononuns and prepositions. However, I would not recommend automating this process if you are to deal with important texts.

#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <set>

using namespace std;

typedef vector<pair<string, int> > subDivision;
set<string> nonUpperCaseAble;

subDivision split(string & cadena, string delim = " "){
    subDivision retorno;
    int pos, inic = 0;
    while((pos = cadena.find_first_of(delim, inic)) != cadena.npos){
        if(pos-inic > 0){
            retorno.push_back(make_pair(cadena.substr(inic, pos-inic), inic));
        }
        inic = pos+1;
    }
    if(inic != cadena.length()){
        retorno.push_back(make_pair(cadena.substr(inic, cadena.length() - inic), inic));
    }
    return retorno;
}

string firstUpper (string & pal){
    pal[0] = toupper(pal[0]);
    return pal;
}

int main()
{
    nonUpperCaseAble.insert("the");
    nonUpperCaseAble.insert("of");
    nonUpperCaseAble.insert("in");
    // ...

    string linea, resultado;
    cout << "Type the line you want to convert: " << endl;
    getline(cin, linea);

    subDivision trozos = split(linea);
    for(int i = 0; i < trozos.size(); i++){
        if(trozos[i].second == 0)
        {
            resultado += firstUpper(trozos[i].first);
        }
        else if (linea[trozos[i].second-1] == ' ')
        {
            if(nonUpperCaseAble.find(trozos[i].first) == nonUpperCaseAble.end())
            {
                resultado += " " + firstUpper(trozos[i].first);
            }else{
                resultado += " " + trozos[i].first;
            }
        }
        else
        {
            resultado += trozos[i].first;
        }       
    }

    cout << resultado << endl;
    getchar();
    return 0;
}
毁我热情 2024-07-11 00:14:06

使用 Perl 你可以这样做:

my $tc_string = join ' ', map { ucfirst($\_) } split /\s+/, $string;

With perl you could do this:

my $tc_string = join ' ', map { ucfirst($\_) } split /\s+/, $string;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文