【发布时间】:2012-12-21 15:10:06
【问题描述】:
我有一个如下所列的字符串。
字符串示例 = "class0 .calss1 .class2 .class3.class4 .class5 class6 .class7";
我需要从这个示例字符串中创建一个 WORDS 列表。
一个 WORD 是一个以句点开头并以:结尾的字符串:
- 空格或
- 另一个时期或
- 字符串结束
注意:这里的重点是 - 拆分基于两个标准 - 句点和空格
我有以下程序。它工作正常。但是,有没有使用LINQ 或Regular Expressions 的更简单/更高效/简洁的方法?
代码
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);
}
}
}
}
}
结果
foreach (string wordItem in wordsCollection)
{
Console.WriteLine(wordItem);
}
参考:
【问题讨论】:
-
@VladL 拆分基于两个标准 - 句点和空格。用 String.Split 怎么办?
-
@MarkByers 我已经用预期结果的截图更新了问题。