我有一個字符串,如下所示。用兩個標準分割字符串
string sample =「class0 .calss1 .class2 .class3.class4 .class5 class6 .class7」;
我需要從此示例字符串中創建WORDS列表。
一個字是與一個週期開始和結尾的字符串:
- 的空間或
- 另一個週期或字符串的
- 端
注:該關鍵點在於 - 分裂基於兩個標準 - 一段時間和一個空白區域
我有以下程序。它工作正常。但是,有沒有使用LINQ
或Regular Expressions
更簡單/更高效/簡潔的方法?
CODE
List<string> wordsCollection = new List<string>();
string sample = " class0 .calss1 .class2 .class3.class4 .class5 class6 .class7";
string word = null;
int stringLength = sample.Length;
int currentCount = 0;
if (stringLength > 0)
{
foreach (Char c in sample)
{
currentCount++;
if (String.IsNullOrEmpty(word))
{
if (c == '.')
{
word = Convert.ToString(c);
}
}
else
{
if (c == ' ')
{
//End Criteria Reached
word = word + Convert.ToString(c);
wordsCollection.Add(word);
word = String.Empty;
}
else if (c == '.')
{
//End Criteria Reached
wordsCollection.Add(word);
word = Convert.ToString(c);
}
else
{
word = word + Convert.ToString(c);
if (stringLength == currentCount)
{
wordsCollection.Add(word);
}
}
}
}
}
RESULT
foreach (string wordItem in wordsCollection)
{
Console.WriteLine(wordItem);
}
參考:
- Splitting up a string, based on predicate
- Is there a better way to get sub-sequences where each item matches a predicate?
- Linq based generic alternate to Predicate<T>?
http://msdn.microsoft.com/en-us/library/vstudio/b873y76a.aspx – VladL
查看[代碼審查] (http://codereview.stackexchange.com) – Default
@VladL拆分基於兩個標準 - 一個句點和一個空格。如何使用String.Split來完成? – Lijo