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);
}
}
}
我打算將每個單詞大寫并再次連接,但是,我無法連接它。我應該如何連接它?
uj5u.com熱心網友回復:
你可以試試這個
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);
uj5u.com熱心網友回復:
以防萬一,你可以這樣做:
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
uj5u.com熱心網友回復:
我建議使用正則運算式:
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是保留并(each!)轉換為(Each!)
模式解釋:
\b - word boundary
\p{Ll} - low case letter
\p{L}* - zero or more letters
\b - word boundary
uj5u.com熱心網友回復:
一種略顯不雅的方法是跟蹤串列中的所有單詞,然后在最后加入。
using System;
using System.Collections.Generic;
class Program{
public static void Main (string[] args){
string Text = "the sentence which each word must be capitalized";
string[] WordArray = new string[8]; //Unused
List<string> WordsCapitalized = new(); //New line
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);
WordsCapitalized.Add(ConcatenatedWord); //new line
}
string FinalString = String.Join(" ", WordsCapitalized); //" " is delimiter between words
}
}
這是基于您發布的代碼構建的,只是為了展示一種簡單的方法。這不一定是我從頭開始的方式。至少,如果這是我的代碼,我會清理它并減少這種方法中的變數數量。
uj5u.com熱心網友回復:
@Ufuk
如果您期望此輸出“每個單詞必須大寫的句子”。那么你的代碼看起來不錯。你已經完成了 95% 的作業。已經用大寫拆分,但您需要將它們存盤在某個地方。所以我創建了一個字串變數來存盤它們。我只寫了兩行。
class Program{
public static void Main (string[] args){
string Text = "the sentence which each word must be capitalized";
string outputText="";
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);
outputText = outputText " " ConcatenatedWord ;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/389965.html
上一篇:pandas的簡單操作
