我有一个字符串,如下所示。
string sample =“class0 .calss1 .class2 .class3.class4 .class5 class6 .class7”;
我需要从此示例字符串创建一个WORDS列表。
WORD是一个以句点开头并以:
结尾的字符串注意:这里的关键点是 - 拆分基于两个标准 - 句号和空格
我有以下计划。它工作正常。但是,使用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);
}
参考:
答案 0 :(得分:5)
您可以使用正则表达式执行此操作。
<强>代码强>
Regex regex = new Regex(@"\.[^ .]+");
var matches = regex.Matches(sample);
string[] result = matches.Cast<Match>().Select(x => x.Value).ToArray();
查看在线工作:ideone
<强>结果强>
.calss1
.class2
.class3
.class4
.class5
.class7
正则表达式的说明
\. Match a dot [^. ]+ Negative character class - anything apart from space or dot (at least one)
相关强>
答案 1 :(得分:1)
string sample = " class0 .calss1 .class2 .class3.class4 .class5 class6 .class7";
string[] words = sample.Split(new char[] {'.'}).Skip(1).Select(x=>
"." + x.Split(new char[] {' '})[0].Trim()).ToArray();
EDIT错过了列表部分:
List<string> words = sample.Split(new char[] {'.'}).Skip(1).Select(x=>
"." + x.Split(new char[] {' '})[0].Trim()).ToList();
答案 2 :(得分:0)
你需要保持。和空间?
如果没有,你可以使用:
sample.split(new char[]{" ", "."}).ToList();
这将为您提供字符串列表。
答案 3 :(得分:0)
string sample = " class0 .calss1 .class2 .class3.class4 .class5 class6 .class7";
sample = Regex.Replace(sample, " ", String.Empty);
string[] arr = sample.Split(new char[] { '.' });