如何在C#中建立首字母大写

如何将文本中的第一个字母设置为大写?

例:

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); } 

它会是这样的:

 // precondition: before must not be an empty string String after = before.Substring(0, 1).ToUpper() + before.Substring(1); 

polygenelubricants的答案适用于大多数情况,但您可能需要考虑文化问题。 您是否希望在当前文化或特定文化中以文化不变的方式利用它? 例如,它可以在土耳其产生重大影响。 所以你可能想要考虑:

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

或者如果您更喜欢String方法:

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

culture可能是CultureInfo.InvariantCulture ,或当前的文化等。

有关此问题的更多信息,请参阅土耳其测试 。

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

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

我用这个变种:

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

我意识到这是一个老post,但我最近遇到了这个问题并用以下方法解决了它。

  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; } 

在下面的示例中,单击按钮执行此简单代码outBox.Text = capSentences(inBox.Text.Trim()); 从上面的框中拉出文本,并在上面的方法运行后将其放在下面的框中。

示例程序

 text = new String( new [] { char.ToUpper(text.First()) } .Concat(text.Skip(1)) .ToArray() ); 

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; } 

这个函数使大写字母成为字符串中所有单词的第一个字母

 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)));; } 

取出单词中的第一个字母,然后将其提取到另一个字符串。

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

试试这段代码:

 char nm[] = "this is a test"; if(char.IsLower(nm[0])) nm[0] = char.ToUpper(nm[0]); //print result: This is a test