我想編寫一個函數,輸入需要包含單詞串並刪除所有單個字符單詞,並返回新的字符串,而不刪除字符字符串清理在C#中
如:
string news = FunctionName("This is a test");
//'news' here should be "This is test".
你能幫忙嗎?
我想編寫一個函數,輸入需要包含單詞串並刪除所有單個字符單詞,並返回新的字符串,而不刪除字符字符串清理在C#中
如:
string news = FunctionName("This is a test");
//'news' here should be "This is test".
你能幫忙嗎?
我敢肯定有使用正則表達式一個更好的答案,但你可以做到以下幾點:
string[] words = news.Split(' ');
StringBuilder builder = new StringBuilder();
foreach (string word in words)
{
if (word.Length > 1)
{
if (builder.ToString().Length ==0)
{
builder.Append(word);
}
else
{
builder.Append(" " + word);
}
}
}
string result = builder.ToString();
關於這個問題的有趣的事情是,想必你也想去掉周圍的空間一個單字母單詞。
string[] oldText = {"This is a test", "a test", "test a"};
foreach (string s in oldText) {
string newText = Regex.Replace(s, @"\s\w\b|\b\w\s", string.Empty);
WL("'" + s + "' --> '" + newText + "'");
}
輸出...
'This is a test' --> 'This is test'
'a test' --> 'test'
'test a' --> 'test'
我剛剛達到這一點。然後我開始考慮以單個字符開始和結尾的字符串,並且我的腦袋開始受到傷害:) – MPritchard 2010-07-30 09:18:52
至少,將正則表達式從循環中移出以實現更高的性能(tm);) – 2010-07-30 11:19:16
爲了清晰起見,使用最優化編碼以作爲爲讀者提供練習;-) – 2010-07-30 11:25:06
LINQ的語法,你可以不喜歡
return string.Join(' ', from string word in input.Split(' ') where word.Length > 1))
強制性LINQ一行代碼:
string.Join(" ", "This is a test".Split(' ').Where(x => x.Length != 1).ToArray())
或者作爲更好的擴展方法:
void Main()
{
var output = "This is a test".WithoutSingleCharacterWords();
}
public static class StringExtensions
{
public static string WithoutSingleCharacterWords(this string input)
{
var longerWords = input.Split(' ').Where(x => x.Length != 1).ToArray();
return string.Join(" ", longerWords);
}
}
+1喜歡使用擴展方法,並且比我的示例清潔多少。我必須正確學習LINQ。 – GenericTypeTea 2010-07-30 09:41:52
如果單詞之間有不同的空格,該怎麼辦? – Grzenio 2010-07-30 10:24:41
@Grzenio你可以使用Regex.Split(input,@「\ s」)來代替,如果你想捕捉標籤和換行符。我只是從問題中通過測試用例:) – 2010-07-30 11:14:31
string str = "This is a test.";
var result = str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);
UPD
使用擴展方法:
public static string RemoveSingleChars(this string str)
{
return str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);
}
//----------Usage----------//
var str = "This is a test.";
var result = str.RemoveSingleChars();
如果你正在做大量的字符串處理,避免正則表達式。這是球慢。我會選擇非正則表達式解決方案作爲更好的答案。 – 2010-07-30 09:13:48
你可以將它作爲字符串的擴展方法來實現,以便於閱讀。 – Peter 2010-07-30 09:17:03