我是新來的c#,我需要修剪一個有很多單詞的句子。我只需要所有單詞中的第一個字符。例如想要除去單詞中第一個字符以外的所有字符
如果一個句子是這樣的。
輸入:Bharat Electrical Limited
=>輸出:BEL
如何在c#中完成此操作?
在此先感謝
我是新來的c#,我需要修剪一個有很多單詞的句子。我只需要所有單詞中的第一個字符。例如想要除去單詞中第一個字符以外的所有字符
如果一個句子是這樣的。
輸入:Bharat Electrical Limited
=>輸出:BEL
如何在c#中完成此操作?
在此先感謝
嘗試
string sentence = "Bharat Electrical Limited";
var result = sentence.Split(' ').Aggregate("", (current, word) => current + word.Substring(0, 1));
編輯:這裏有一個簡短的explanantion:
sentence.Split(' ')
拆分字符串劃分爲元素基於空間(」「)
.Aggregate("", (current, word) => current + word.Substring(0, 1));
是linq表達式遍歷每個單詞,檢索上面執行的操作,並且
word.Substring(0, 1)
返回的每一個字要Split串入的話
第一件事的第一個字母,再從每個單詞第一個字母。您可以通過一個簡單的像下面的循環做到這一點:
string inputStr = "Bharat Electrical Limited";
List<char> firstChars = new List<char>();
foreach (string word in inputStr.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries))
{
firstChars.Add(word[0]); // Collecting first chars of each word
}
string outputStr = String.Join("", firstChars);
,這將是這個短方式:
string inputStr = "Bharat Electrical Limited";
string shortWord = String.Join("", inputStr.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries).Select(x => x[0]));
如果每個字符串的第一個字符是不大寫,那麼你可以使用以下任何選項。
爲此,您可以使用下面的代碼:
inputStr = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(inputStr.ToLower());
這可以通過以下方式實現:
firstChars.Add(char.ToUpper(word[0])); // For the first case
.Select(x => char.ToUpper(x[0])) // For the second case
Here你可以找到一個工作示例上述所有情況下
你可以使用'String.Concat'而不是'String.Join'。 –
@ErenErsönmez:我認爲'String.Join'比'Concatenation'好。因爲'依靠內部的StringBuilder來構建連接的字符串',不是嗎?那麼你爲什麼建議使用'Concatenation'? –
另外,爲什麼不簡單地''選擇(x => x [0] .ToUpper())'?而不是將整個字符串更改爲標題大小寫, – Jcl
你可以做這樣的事情 -
string sentence = "Bharat Electrical Limited";
//Split the words
var letters = sentence.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
//Take firsst letter of every word
var myAbbWord = letters.Aggregate(string.Empty, (current, letter) => current + letter.First());
myAbbWord
應顯示BEL你。
以下是解決方案。
我希望它有幫助。
string str1 = "Bharat Electrical Limited";
var resultList = str1.Split(' ');
string result = resultList.Aggregate(String.Empty, (current, word) => current + word.First());
簡單的方法是:
string inputStr = "Bharat Electrical Limited";
string result = new String(inputStr.Split(' ').Select(word => (word[0])).ToArray());
// BEL
您需要添加using System.Linq;
到您的源文件。
邏輯是:
拆分串入陣列或字(由空格分隔),然後項目此數組通過選擇每個字符串的第一個字符。結果是第一個字符的數組。然後使用字符串重載構造函數取char數組,構造結果字符串。
這是何許件事是很容易用正則表達式來實現:
s = Regex.Replace(s, @"(\S)\S*\s*", "$1");
這有效地匹配連續的非空格字符,後跟空格,並取代它的第一個字符的整個序列。
哇,在羣中脫穎而出。 :) –
這可能看起來更對你友好
string intput = "Bharat Electrical Limited";
string output = string.Join("",intput.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries)
.Select(a => a.First()));
先拆你的輸入sentense與空間,然後在string
使用First()
擴展來獲得字符串的第一個字符
使用此方法
string inputStr = "Bharat Electrical Limited";
var arrayString = string.Join("", inputStr.Split(' ').Select(x => x[0]));
歡迎來到Stack Overflow和C#,你嘗試了什麼? –
拆分空格,取第一個結果 – Jonesopolis
我試着修剪字符串,它沒有發生 –