2010-06-13 114 views
4

在C#中是否有任何內置的方式將文本分割成單詞和分隔符數組? 我想要的是:C#:字符串拆分返回字符串列表和分隔符列表?

text = "word1 + word2 - word3"; 
string[] words = text.Split(new char[] { '+', '-'}); 
//Need list '+', '-' here? 

任何想法?很明顯,我可以用手處理文本...... :)

+0

如果您編輯您的帖子顯示的話陣列中的輸出應該是什麼您的輸入例如這將是有益的。 – 2010-06-13 11:46:45

+0

單詞數組將包含Split()通常返回的內容, 例如words = {「word1」,「word2」,「word3」} 另外我正在尋找delims = {'+',' - '} – 2010-06-13 12:07:26

回答

9

使用Regex.split()的捕獲括號http://msdn.microsoft.com/en-us/library/byy2946e.aspx

string input = @"07/14/2007"; 
string pattern = @"(-)|(/)"; 

foreach (string result in Regex.Split(input, pattern)) 
{ 
    Console.WriteLine("'{0}'", result); 
} 
// In .NET 1.0 and 1.1, the method returns an array of 
// 3 elements, as follows: 
// '07' 
// '14' 
// '2007' 
// 
// In .NET 2.0, the method returns an array of 
// 5 elements, as follows: 
// '07' 
// '/' 
// '14' 
// '/' 
// '2007' 
+0

你正在使用.Net 2.0 – Sijin 2010-06-13 11:39:52

0

不是我知道,但我想你可以用正則表達式來做。只需編寫它只拾取您的分隔符,然後使用Regex.Matches並且返回的集合應包含分隔符。有關更多信息,請參閱here,其中包括簡短樣本。