[英]Splitting a String with two criteria
我有一個字符串,如下所示。
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);
}
}
}
}
}
結果
foreach (string wordItem in wordsCollection)
{
Console.WriteLine(wordItem);
}
參考:
您可以使用正則表達式執行此操作。
碼
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)
有關
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();
編輯錯過了列表部分:
List<string> words = sample.Split(new char[] {'.'}).Skip(1).Select(x=>
"." + x.Split(new char[] {' '})[0].Trim()).ToList();
你需要保持。 和空間?
如果沒有,你可以使用:
sample.split(new char[]{" ", "."}).ToList();
這將為您提供一個字符串列表。
string sample = " class0 .calss1 .class2 .class3.class4 .class5 class6 .class7";
sample = Regex.Replace(sample, " ", String.Empty);
string[] arr = sample.Split(new char[] { '.' });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.