using System;
class Program{
public static void Main (string[] args){
string Text = "the sentence which each word must be capitalized";
string[] WordArray = new string[8];
foreach (string Word in Text.Split(' ')){
string CapitalizedFirstLetter = Word.Substring(0, 1).ToUpper();
string RestOfWord = Word.Substring(1, Word.Length-1);
string ConcatenatedWord = string.Concat(CapitalizedFirstLetter, RestOfWord);
}
}
}
我本来打算将每个单词大写,然后再将其连接起来,但是,我无法将其连接起来。我应该如何连接它?
你可以试试这个
string text = "the sentence which each word must be capitalized";
var words = text.Split(" ");
for (var i = 0; i < words.Length; i++) words[i] =
Char.ToUpper(words[i][0]).ToString()+words[i].Substring(1);
text = string.Join(" ", words);
以防万一,你可以这样做:
string Text = "the sentence which each word must be capitalized";
Console.WriteLine(CultureInfo.InvariantCulture.TextInfo.ToTitleCase(Text));
输出:
The Sentence Which Each Word Must Be Capitalized
我建议使用正则表达式:
using System.Text.RegularExpressions;
...
string Text = "the sentence which (each!) word must BE capitalized";
string result = Regex.Replace(Text,
@"\b\p{Ll}\p{L}*\b",
match => {
string word = match.Value;
//TODO: Some logic if we want to capitalize the word
// if (...) return word;
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word);
}
);
Console.Write(result);
成果:
The Sentence Which (Each!) Word Must BE Capitalized
注意,BE
被保留,并且(每个!)代码>转换为
(每个!)代码>
模式解释:
\b - word boundary
\p{Ll} - low case letter
\p{L}* - zero or more letters
\b - word boundary