我有一个字符串,如下所示.
string sample ="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);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果
foreach (string wordItem in wordsCollection)
{
Console.WriteLine(wordItem);
}
Run Code Online (Sandbox Code Playgroud)

参考:
您可以使用正则表达式执行此操作.
码
Regex regex = new Regex(@"\.[^ .]+");
var matches = regex.Matches(sample);
string[] result = matches.Cast<Match>().Select(x => x.Value).ToArray();
Run Code Online (Sandbox Code Playgroud)
看到它在线工作:ideone
结果
.calss1
.class2
.class3
.class4
.class5
.class7
Run Code Online (Sandbox Code Playgroud)
正则表达式的解释
\. Match a dot [^. ]+ Negative character class - anything apart from space or dot (at least one)
有关