开发者

C#: String split returning list of strings AND list of delimiters?

Is there any inbuilt way in C# to split a text into an array of words and delimiters? What I want is:

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

Any ideas? Obviously I can just process the text by hand... :)


Use Regex.split() with capturing parentheses 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'


Not that I'm aware of, but I suppose you could do it with a regular expression. Just write it to pick up only your delimiters and then use Regex.Matches and the collection that is returned should contain the delimiters. See here for more info including a short sample.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜