简体   繁体   English

如何在 C# 中将首字母大写

[英]How to make a first letter capital in C#

How can the first letter in a text be set to capital?如何将文本中的第一个字母设置为大写?

Example:例子:

it is a text.  = It is a text.
public static string ToUpperFirstLetter(this string source)
{
    if (string.IsNullOrEmpty(source))
        return string.Empty;
    // convert to char array of the string
    char[] letters = source.ToCharArray();
    // upper case the first char
    letters[0] = char.ToUpper(letters[0]);
    // return the array made of the new char array
    return new string(letters);
}

It'll be something like this:它会是这样的:

// precondition: before must not be an empty string

String after = before.Substring(0, 1).ToUpper() + before.Substring(1);

polygenelubricants' answer is fine for most cases, but you potentially need to think about cultural issues. polygenelubricants 的答案在大多数情况下都很好,但您可能需要考虑文化问题。 Do you want this capitalized in a culture-invariant way, in the current culture, or a specific culture?您希望在当前文化或特定文化中以文化不变的方式将其大写吗? It can make a big difference in Turkey, for example.例如,它可以在土耳其产生重大影响。 So you may want to consider:所以你可能要考虑:

CultureInfo culture = ...;
text = char.ToUpper(text[0], culture) + text.Substring(1);

or if you prefer methods on String :或者,如果您更喜欢String上的方法:

CultureInfo culture = ...;
text = text.Substring(0, 1).ToUpper(culture) + text.Substring(1);

where culture might be CultureInfo.InvariantCulture , or the current culture etc.其中culture可能是CultureInfo.InvariantCulture或当前文化等。

For more on this problem, see the Turkey Test .有关此问题的更多信息,请参阅土耳其测试

如果您使用的是 C#,请尝试以下代码:

Microsoft.VisualBasic.StrConv(sourceString, Microsoft.VisualBasic.vbProperCase)

I use this variant:我使用这个变体:

 private string FirstLetterCapital(string str)
        {
            return Char.ToUpper(str[0]) + str.Remove(0, 1);            
        }

I realize this is an old post, but I recently had this problem and solved it with the following method.我意识到这是一个旧帖子,但我最近遇到了这个问题并用以下方法解决了它。

    private string capSentences(string str)
    {
        string s = "";

        if (str[str.Length - 1] == '.')
            str = str.Remove(str.Length - 1, 1);

        char[] delim = { '.' };

        string[] tokens = str.Split(delim);

        for (int i = 0; i < tokens.Length; i++)
        {
            tokens[i] = tokens[i].Trim();

            tokens[i] = char.ToUpper(tokens[i][0]) + tokens[i].Substring(1);

            s += tokens[i] + ". ";
        } 

        return s;
    }

In the sample below clicking on the button executes this simple code outBox.Text = capSentences(inBox.Text.Trim());在下面的示例中,单击按钮会执行这个简单的代码outBox.Text = capSentences(inBox.Text.Trim()); which pulls the text from the upper box and puts it in the lower box after the above method runs on it.在上面的方法运行后,它从上框中提取文本并将其放入下框中。

示例程序

Take the first letter out of the word and then extract it to the other string.从单词中取出第一个字母,然后将其提取到另一个字符串中。

strFirstLetter = strWord.Substring(0, 1).ToUpper();
strFullWord = strFirstLetter + strWord.Substring(1);

If you are sure that str variable is valid (never an empty-string or null), try:如果您确定str变量有效(绝不是空字符串或 null),请尝试:

str = Char.ToUpper(str[0]) + str[1..];

Unlike the other solutions that use Substring, this one does not do additional string allocations.与使用 Substring 的其他解决方案不同,此解决方案不进行额外的字符串分配。 This example basically concatenates char with ReadOnlySpan<char> .这个例子基本上将charReadOnlySpan<char>连接起来。

    static String UppercaseWords(String BadName)
    {
        String FullName = "";

        if (BadName != null)
        {
            String[] FullBadName = BadName.Split(' ');
            foreach (string Name in FullBadName)
            {
                String SmallName = "";
                if (Name.Length > 1)
                {
                    SmallName = char.ToUpper(Name[0]) + Name.Substring(1).ToLower();
                }
                else
                {
                    SmallName = Name.ToUpper();
                }
                FullName = FullName + " " + SmallName;
            }

        }
        FullName = FullName.Trim();
        FullName = FullName.TrimEnd();
        FullName = FullName.TrimStart();
        return FullName;
    }

this functions makes capital the first letter of all words in a string此函数使大写成为字符串中所有单词的首字母

public static string FormatSentence(string source)
    {
        var words = source.Split(' ').Select(t => t.ToCharArray()).ToList();
        words.ForEach(t =>
        {
            for (int i = 0; i < t.Length; i++)
            {
                t[i] = i.Equals(0) ? char.ToUpper(t[i]) : char.ToLower(t[i]);
            }
        });
        return string.Join(" ", words.Select(t => new string(t)));;
    }
text = new String(
    new [] { char.ToUpper(text.First()) }
    .Concat(text.Skip(1))
    .ToArray()
);
string Input = "    it is my text";

Input = Input.TrimStart();

//Create a char array
char[] Letters = Input.ToCharArray();

//Make first letter a capital one
string First = char.ToUpper(Letters[0]).ToString();

//Concatenate 
string Output = string.Concat(First,Input.Substring(1));

Try this code snippet:试试这个代码片段:

char nm[] = "this is a test";

if(char.IsLower(nm[0]))  nm[0] = char.ToUpper(nm[0]);

//print result: This is a test
string str = "it is a text";

// first use the .Trim() method to get rid of all the unnecessary space at the begining and the end for exemple (" This string ".Trim() is gonna output "This string"). // 首先使用 .Trim() 方法去除开头和结尾所有不必要的空间,例如(“This string”.Trim() 将输出“This string”)。

str = str.Trim();

char theFirstLetter = str[0]; // this line is to take the first letter of the string at index 0. // 这一行是在索引 0 处取字符串的第一个字母。

theFirstLetter.ToUpper(); // .ToTupper() methode to uppercase the firstletter. // .ToTupper() 方法将首字母大写。

str = theFirstLetter + str.substring(1); // we add the first letter that we uppercased and add the rest of the string by using the str.substring(1) (str.substring(1) to skip the first letter at index 0 and only print the letters from the index 1 to the last index.) Console.WriteLine(str); // 我们添加我们大写的第一个字母并通过使用 str.substring(1) (str.substring(1) 跳过索引 0 处的第一个字母并仅打印索引 1 中的字母来添加字符串的其余部分到最后一个索引。) Console.WriteLine(str); // now it should output "It is a text" // 现在它应该输出“It is a text”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字符串C#中的首字母大写 - First letter capital in string c# C#Regex首字母大写,其余小写 - C# Regex first letter capital the rest lower case C#:如何仅从字符串中返回第一组大写字母单词? - C#: How can I only return the first set of capital letter words from a string? 如何使用c#代码制作每个单词的第一个字母 - how to make 1st letter of each word capital using c# code C#如何使标签的第一个字母可见 - C# How to make visible first letter of label API Json 响应 C# 对象的首字母大写属性 - API Json response to C# Object with capital case properties first letter 如何检查字符串的第一个字符,如果是字母,C# 中的任何字母 - How to check first character of a string if a letter, any letter in C# 在c#中使用正则表达式来查找字母然后用大写字母和其他字符的移位表单? - Regular Expression in c# to find letter then \ with capital letter for letter and Shift press form of other charecter? 如何在linq C#中计算字符串的字符串数组中的第一个字母 - How to Count in a string array for string First letter in linq C# C#如何在方法中将字符串的第一个字母作为char返回? - C# How to return first letter from a string as a char in a method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM