Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own?
是否有一种简单的方法可以将字符串的第一个字母大写并降低其余部分?是否有内置方法或我需要自己制作?
17 个解决方案
#1
255
TextInfo.ToTitleCase()
capitalizes the first character in each token of a string.
If there is no need to maintain Acronym Uppercasing, then you should include ToLower()
.
TextInfo.ToTitleCase()将字符串的每个标记中的第一个字符大写。如果不需要维护Acronym Uppercasing,那么您应该包括ToLower()。
string s = "JOHN DOE";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
// Produces "John Doe"
If CurrentCulture is unavailable, use:
如果CurrentCulture不可用,请使用:
string s = "JOHN DOE";
s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());
See the MSDN Link for a detailed description.
有关详细说明,请参阅MSDN链接。
#2
117
CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello world");
#3
30
String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);
The above code wont work .....
上面的代码不会工作.....
so put the below code by convert to lower then apply the function
所以把下面的代码转换为低,然后应用函数
String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower());
#4
12
There are some cases that CultureInfo.CurrentCulture.TextInfo.ToTitleCase
cannot handle, for example : the apostrophe '
.
有些情况下CultureInfo.CurrentCulture.TextInfo.ToTitleCase无法处理,例如:撇号'。
string input = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("o'reilly, m'grego, d'angelo");
// input = O'reilly, M'grego, D'angelo
A regex can also be used \b[a-zA-Z]
to identify the starting character of a word after a word boundary \b
, then we need just to replace the match by its upper case equivalence thanks to the Regex.Replace(string input,string pattern,MatchEvaluator evaluator)
method :
也可以使用正则表达式\ b [a-zA-Z]来识别单词边界\ b之后的单词的起始字符,然后我们只需要通过Regex.Replace替换匹配的大写等价(字符串输入,字符串模式,MatchEvaluator求值程序)方法:
string input = "o'reilly, m'grego, d'angelo";
input = Regex.Replace(input.ToLower(), @"\b[a-zA-Z]", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo
The regex can be tuned if needed, for instance, if we want to handle the MacDonald
and McFry
cases the regex becomes : (?<=\b(?:mc|mac)?)[a-zA-Z]
如果需要,可以调整正则表达式,例如,如果我们想要处理MacDonald和McFry情况,则正则表达式变为:(?<= \ b(?:mc | mac)?)[a-zA-Z]
string input = "o'reilly, m'grego, d'angelo, macdonald's, mcfry";
input = Regex.Replace(input.ToLower(), @"(?<=\b(?:mc|mac)?)[a-zA-Z]", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo, MacDonald'S, McFry
If we need to handle more prefixes we only need to modify the group (?:mc|mac)
, for example to add french prefixes du, de
: (?:mc|mac|du|de)
.
如果我们需要处理更多的前缀,我们只需要修改组(?:mc | mac),例如添加法语前缀du,de:(?:mc | mac | du | de)。
Finally, we can realize that this regex will also match the case MacDonald'S
for the last 's
so we need to handle it in the regex with a negative look behind (?<!'s\b)
. At the end we have :
最后,我们可以意识到这个正则表达式也将匹配麦当劳的最后一个案例,所以我们需要在正则表达式中处理它,背后有负面看法(?
string input = "o'reilly, m'grego, d'angelo, macdonald's, mcfry";
input = Regex.Replace(input.ToLower(), @"(?<=\b(?:mc|mac)?)[a-zA-Z](?<!'s\b)", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo, MacDonald's, McFry
#5
7
Mc and Mac are common surname prefixes throughout the US, and there are others. TextInfo.ToTitleCase doesn't handle those cases and shouldn't be used for this purpose. Here's how I'm doing it:
Mc和Mac是整个美国常见的姓氏前缀,还有其他人。 TextInfo.ToTitleCase不处理这些情况,不应该用于此目的。我是这样做的:
public static string ToTitleCase(string str)
{
string result = str;
if (!string.IsNullOrEmpty(str))
{
var words = str.Split(' ');
for (int index = 0; index < words.Length; index++)
{
var s = words[index];
if (s.Length > 0)
{
words[index] = s[0].ToString().ToUpper() + s.Substring(1);
}
}
result = string.Join(" ", words);
}
return result;
}
#7
4
The most direct option is going to be to use the ToTitleCase function that is available in .NET which should take care of the name most of the time. As edg pointed out there are some names that it will not work for, but these are fairly rare so unless you are targeting a culture where such names are common it is not necessary something that you have to worry too much about.
最直接的选择是使用.NET中可用的ToTitleCase函数,它应该在大多数时候处理名称。正如edg所指出的那样,有一些名称不适用,但这些名称相当罕见,所以除非你的目标是这种名称很常见的文化,否则你不必过分担心。
However if you are not working with a .NET langauge, then it depends on what the input looks like - if you have two separate fields for the first name and the last name then you can just capitalize the first letter lower the rest of it using substrings.
但是,如果您不使用.NET语言,那么它取决于输入的内容 - 如果您有第一个名称和姓氏的两个单独的字段,那么您可以使用第一个字母将其余部分大写下来子。
firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();
lastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();
However, if you are provided multiple names as part of the same string then you need to know how you are getting the information and split it accordingly. So if you are getting a name like "John Doe" you an split the string based upon the space character. If it is in a format such as "Doe, John" you are going to need to split it based upon the comma. However, once you have it split apart you just apply the code shown previously.
但是,如果为同一个字符串提供了多个名称,那么您需要知道如何获取信息并进行相应的拆分。因此,如果你得到一个像“John Doe”这样的名字,你可以根据空格字符分割字符串。如果它的格式如“Doe,John”,则需要根据逗号分割它。但是,一旦你拆分它,你只需应用前面显示的代码。
#8
3
CultureInfo.CurrentCulture.TextInfo.ToTitleCase ("my name");
CultureInfo.CurrentCulture.TextInfo.ToTitleCase(“我的名字”);
returns ~ My Name
返回〜我的名字
But the problem still exists with names like McFly as stated earlier.
但问题仍然存在于像之前所述的McFly这样的名字。
#9
3
I use my own method to get this fixed:
我使用自己的方法来解决这个问题:
For example the phrase: "hello world. hello this is the * world." will be "Hello World. Hello This Is The * World.". Regex \b (start of a word) \w (first charactor of the word) will do the trick.
例如短语:“hello world。你好,这是*世界。”将是“Hello World。你好,这是*世界。”。正则表达式\ b(单词的开头)\ w(单词的第一个字符)将起作用。
/// <summary>
/// Makes each first letter of a word uppercase. The rest will be lowercase
/// </summary>
/// <param name="Phrase"></param>
/// <returns></returns>
public static string FormatWordsWithFirstCapital(string Phrase)
{
MatchCollection Matches = Regex.Matches(Phrase, "\\b\\w");
Phrase = Phrase.ToLower();
foreach (Match Match in Matches)
Phrase = Phrase.Remove(Match.Index, 1).Insert(Match.Index, Match.Value.ToUpper());
return Phrase;
}
#10
2
The suggestions to use ToTitleCase won't work for strings that are all upper case. So you are gonna have to call ToUpper on the first char and ToLower on the remaining characters.
使用ToTitleCase的建议不适用于全部大写的字符串。所以你必须在第一个char上调用ToUpper,在剩下的字符上调用ToLower。
#11
2
This class does the trick. You can add new prefixes to the _prefixes static string array.
这个类可以解决问题。您可以向_prefixes静态字符串数组添加新前缀。
public static class StringExtensions
{
public static string ToProperCase( this string original )
{
if( String.IsNullOrEmpty( original ) )
return original;
string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );
return result;
}
public static string WordToProperCase( this string word )
{
if( String.IsNullOrEmpty( word ) )
return word;
if( word.Length > 1 )
return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );
return word.ToUpper( CultureInfo.CurrentCulture );
}
private static readonly Regex _properNameRx = new Regex( @"\b(\w+)\b" );
private static readonly string[] _prefixes = {
"mc"
};
private static string HandleWord( Match m )
{
string word = m.Groups[1].Value;
foreach( string prefix in _prefixes )
{
if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )
return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();
}
return word.WordToProperCase();
}
}
#12
1
If your using vS2k8, you can use an extension method to add it to the String class:
如果您使用vS2k8,则可以使用扩展方法将其添加到String类:
public static string FirstLetterToUpper(this String input)
{
return input = input.Substring(0, 1).ToUpper() +
input.Substring(1, input.Length - 1);
}
#13
0
To get round some of the issues/problems that have ben highlighted I would suggest converting the string to lower case first and then call the ToTitleCase method. You could then use IndexOf(" Mc") or IndexOf(" O\'") to determine special cases that need more specific attention.
为了解决一些突出显示的问题/问题,我建议先将字符串转换为小写,然后调用ToTitleCase方法。然后,您可以使用IndexOf(“Mc”)或IndexOf(“O”)来确定需要更具体关注的特殊情况。
inputString = inputString.ToLower();
inputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);
int indexOfMc = inputString.IndexOf(" Mc");
if(indexOfMc > 0)
{
inputString.Substring(0, indexOfMc + 3) + inputString[indexOfMc + 3].ToString().ToUpper() + inputString.Substring(indexOfMc + 4);
}
#14
0
I like this way:
我喜欢这样:
using System.Globalization;
...
TextInfo myTi = new CultureInfo("en-Us",false).TextInfo;
string raw = "THIS IS ALL CAPS";
string firstCapOnly = myTi.ToTitleCase(raw.ToLower());
Lifted from this MSDN article.
解除了这篇MSDN文章。
#15
0
Hope this helps you.
希望这对你有所帮助。
String fName = "firstname";
String lName = "lastname";
String capitalizedFName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fName);
String capitalizedLName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lName);
#16
0
public static string ConvertToCaptilize(string input)
{
if (!string.IsNullOrEmpty(input))
{
string[] arrUserInput = input.Split(' ');
// Initialize a string builder object for the output
StringBuilder sbOutPut = new StringBuilder();
// Loop thru each character in the string array
foreach (string str in arrUserInput)
{
if (!string.IsNullOrEmpty(str))
{
var charArray = str.ToCharArray();
int k = 0;
foreach (var cr in charArray)
{
char c;
c = k == 0 ? char.ToUpper(cr) : char.ToLower(cr);
sbOutPut.Append(c);
k++;
}
}
sbOutPut.Append(" ");
}
return sbOutPut.ToString();
}
return string.Empty;
}
#17
-1
Like edg indicated, you'll need a more complex algorithm to handle special names (this is probably why many places force everything to upper case).
就像edg指出的那样,你需要一个更复杂的算法来处理特殊名称(这可能就是为什么很多地方强迫一切都是大写的)。
Something like this untested c# should handle the simple case you requested:
像这样未经测试的c#应该处理你请求的简单案例:
public string SentenceCase(string input)
{
return input(0, 1).ToUpper + input.Substring(1).ToLower;
}
#1
255
TextInfo.ToTitleCase()
capitalizes the first character in each token of a string.
If there is no need to maintain Acronym Uppercasing, then you should include ToLower()
.
TextInfo.ToTitleCase()将字符串的每个标记中的第一个字符大写。如果不需要维护Acronym Uppercasing,那么您应该包括ToLower()。
string s = "JOHN DOE";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
// Produces "John Doe"
If CurrentCulture is unavailable, use:
如果CurrentCulture不可用,请使用:
string s = "JOHN DOE";
s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());
See the MSDN Link for a detailed description.
有关详细说明,请参阅MSDN链接。
#2
117
CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello world");
#3
30
String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);
The above code wont work .....
上面的代码不会工作.....
so put the below code by convert to lower then apply the function
所以把下面的代码转换为低,然后应用函数
String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower());
#4
12
There are some cases that CultureInfo.CurrentCulture.TextInfo.ToTitleCase
cannot handle, for example : the apostrophe '
.
有些情况下CultureInfo.CurrentCulture.TextInfo.ToTitleCase无法处理,例如:撇号'。
string input = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("o'reilly, m'grego, d'angelo");
// input = O'reilly, M'grego, D'angelo
A regex can also be used \b[a-zA-Z]
to identify the starting character of a word after a word boundary \b
, then we need just to replace the match by its upper case equivalence thanks to the Regex.Replace(string input,string pattern,MatchEvaluator evaluator)
method :
也可以使用正则表达式\ b [a-zA-Z]来识别单词边界\ b之后的单词的起始字符,然后我们只需要通过Regex.Replace替换匹配的大写等价(字符串输入,字符串模式,MatchEvaluator求值程序)方法:
string input = "o'reilly, m'grego, d'angelo";
input = Regex.Replace(input.ToLower(), @"\b[a-zA-Z]", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo
The regex can be tuned if needed, for instance, if we want to handle the MacDonald
and McFry
cases the regex becomes : (?<=\b(?:mc|mac)?)[a-zA-Z]
如果需要,可以调整正则表达式,例如,如果我们想要处理MacDonald和McFry情况,则正则表达式变为:(?<= \ b(?:mc | mac)?)[a-zA-Z]
string input = "o'reilly, m'grego, d'angelo, macdonald's, mcfry";
input = Regex.Replace(input.ToLower(), @"(?<=\b(?:mc|mac)?)[a-zA-Z]", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo, MacDonald'S, McFry
If we need to handle more prefixes we only need to modify the group (?:mc|mac)
, for example to add french prefixes du, de
: (?:mc|mac|du|de)
.
如果我们需要处理更多的前缀,我们只需要修改组(?:mc | mac),例如添加法语前缀du,de:(?:mc | mac | du | de)。
Finally, we can realize that this regex will also match the case MacDonald'S
for the last 's
so we need to handle it in the regex with a negative look behind (?<!'s\b)
. At the end we have :
最后,我们可以意识到这个正则表达式也将匹配麦当劳的最后一个案例,所以我们需要在正则表达式中处理它,背后有负面看法(?
string input = "o'reilly, m'grego, d'angelo, macdonald's, mcfry";
input = Regex.Replace(input.ToLower(), @"(?<=\b(?:mc|mac)?)[a-zA-Z](?<!'s\b)", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo, MacDonald's, McFry
#5
7
Mc and Mac are common surname prefixes throughout the US, and there are others. TextInfo.ToTitleCase doesn't handle those cases and shouldn't be used for this purpose. Here's how I'm doing it:
Mc和Mac是整个美国常见的姓氏前缀,还有其他人。 TextInfo.ToTitleCase不处理这些情况,不应该用于此目的。我是这样做的:
public static string ToTitleCase(string str)
{
string result = str;
if (!string.IsNullOrEmpty(str))
{
var words = str.Split(' ');
for (int index = 0; index < words.Length; index++)
{
var s = words[index];
if (s.Length > 0)
{
words[index] = s[0].ToString().ToUpper() + s.Substring(1);
}
}
result = string.Join(" ", words);
}
return result;
}
#6
#7
4
The most direct option is going to be to use the ToTitleCase function that is available in .NET which should take care of the name most of the time. As edg pointed out there are some names that it will not work for, but these are fairly rare so unless you are targeting a culture where such names are common it is not necessary something that you have to worry too much about.
最直接的选择是使用.NET中可用的ToTitleCase函数,它应该在大多数时候处理名称。正如edg所指出的那样,有一些名称不适用,但这些名称相当罕见,所以除非你的目标是这种名称很常见的文化,否则你不必过分担心。
However if you are not working with a .NET langauge, then it depends on what the input looks like - if you have two separate fields for the first name and the last name then you can just capitalize the first letter lower the rest of it using substrings.
但是,如果您不使用.NET语言,那么它取决于输入的内容 - 如果您有第一个名称和姓氏的两个单独的字段,那么您可以使用第一个字母将其余部分大写下来子。
firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();
lastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();
However, if you are provided multiple names as part of the same string then you need to know how you are getting the information and split it accordingly. So if you are getting a name like "John Doe" you an split the string based upon the space character. If it is in a format such as "Doe, John" you are going to need to split it based upon the comma. However, once you have it split apart you just apply the code shown previously.
但是,如果为同一个字符串提供了多个名称,那么您需要知道如何获取信息并进行相应的拆分。因此,如果你得到一个像“John Doe”这样的名字,你可以根据空格字符分割字符串。如果它的格式如“Doe,John”,则需要根据逗号分割它。但是,一旦你拆分它,你只需应用前面显示的代码。
#8
3
CultureInfo.CurrentCulture.TextInfo.ToTitleCase ("my name");
CultureInfo.CurrentCulture.TextInfo.ToTitleCase(“我的名字”);
returns ~ My Name
返回〜我的名字
But the problem still exists with names like McFly as stated earlier.
但问题仍然存在于像之前所述的McFly这样的名字。
#9
3
I use my own method to get this fixed:
我使用自己的方法来解决这个问题:
For example the phrase: "hello world. hello this is the * world." will be "Hello World. Hello This Is The * World.". Regex \b (start of a word) \w (first charactor of the word) will do the trick.
例如短语:“hello world。你好,这是*世界。”将是“Hello World。你好,这是*世界。”。正则表达式\ b(单词的开头)\ w(单词的第一个字符)将起作用。
/// <summary>
/// Makes each first letter of a word uppercase. The rest will be lowercase
/// </summary>
/// <param name="Phrase"></param>
/// <returns></returns>
public static string FormatWordsWithFirstCapital(string Phrase)
{
MatchCollection Matches = Regex.Matches(Phrase, "\\b\\w");
Phrase = Phrase.ToLower();
foreach (Match Match in Matches)
Phrase = Phrase.Remove(Match.Index, 1).Insert(Match.Index, Match.Value.ToUpper());
return Phrase;
}
#10
2
The suggestions to use ToTitleCase won't work for strings that are all upper case. So you are gonna have to call ToUpper on the first char and ToLower on the remaining characters.
使用ToTitleCase的建议不适用于全部大写的字符串。所以你必须在第一个char上调用ToUpper,在剩下的字符上调用ToLower。
#11
2
This class does the trick. You can add new prefixes to the _prefixes static string array.
这个类可以解决问题。您可以向_prefixes静态字符串数组添加新前缀。
public static class StringExtensions
{
public static string ToProperCase( this string original )
{
if( String.IsNullOrEmpty( original ) )
return original;
string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );
return result;
}
public static string WordToProperCase( this string word )
{
if( String.IsNullOrEmpty( word ) )
return word;
if( word.Length > 1 )
return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );
return word.ToUpper( CultureInfo.CurrentCulture );
}
private static readonly Regex _properNameRx = new Regex( @"\b(\w+)\b" );
private static readonly string[] _prefixes = {
"mc"
};
private static string HandleWord( Match m )
{
string word = m.Groups[1].Value;
foreach( string prefix in _prefixes )
{
if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )
return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();
}
return word.WordToProperCase();
}
}
#12
1
If your using vS2k8, you can use an extension method to add it to the String class:
如果您使用vS2k8,则可以使用扩展方法将其添加到String类:
public static string FirstLetterToUpper(this String input)
{
return input = input.Substring(0, 1).ToUpper() +
input.Substring(1, input.Length - 1);
}
#13
0
To get round some of the issues/problems that have ben highlighted I would suggest converting the string to lower case first and then call the ToTitleCase method. You could then use IndexOf(" Mc") or IndexOf(" O\'") to determine special cases that need more specific attention.
为了解决一些突出显示的问题/问题,我建议先将字符串转换为小写,然后调用ToTitleCase方法。然后,您可以使用IndexOf(“Mc”)或IndexOf(“O”)来确定需要更具体关注的特殊情况。
inputString = inputString.ToLower();
inputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);
int indexOfMc = inputString.IndexOf(" Mc");
if(indexOfMc > 0)
{
inputString.Substring(0, indexOfMc + 3) + inputString[indexOfMc + 3].ToString().ToUpper() + inputString.Substring(indexOfMc + 4);
}
#14
0
I like this way:
我喜欢这样:
using System.Globalization;
...
TextInfo myTi = new CultureInfo("en-Us",false).TextInfo;
string raw = "THIS IS ALL CAPS";
string firstCapOnly = myTi.ToTitleCase(raw.ToLower());
Lifted from this MSDN article.
解除了这篇MSDN文章。
#15
0
Hope this helps you.
希望这对你有所帮助。
String fName = "firstname";
String lName = "lastname";
String capitalizedFName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fName);
String capitalizedLName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lName);
#16
0
public static string ConvertToCaptilize(string input)
{
if (!string.IsNullOrEmpty(input))
{
string[] arrUserInput = input.Split(' ');
// Initialize a string builder object for the output
StringBuilder sbOutPut = new StringBuilder();
// Loop thru each character in the string array
foreach (string str in arrUserInput)
{
if (!string.IsNullOrEmpty(str))
{
var charArray = str.ToCharArray();
int k = 0;
foreach (var cr in charArray)
{
char c;
c = k == 0 ? char.ToUpper(cr) : char.ToLower(cr);
sbOutPut.Append(c);
k++;
}
}
sbOutPut.Append(" ");
}
return sbOutPut.ToString();
}
return string.Empty;
}
#17
-1
Like edg indicated, you'll need a more complex algorithm to handle special names (this is probably why many places force everything to upper case).
就像edg指出的那样,你需要一个更复杂的算法来处理特殊名称(这可能就是为什么很多地方强迫一切都是大写的)。
Something like this untested c# should handle the simple case you requested:
像这样未经测试的c#应该处理你请求的简单案例:
public string SentenceCase(string input)
{
return input(0, 1).ToUpper + input.Substring(1).ToLower;
}