Question

I have the following string:

/A//B/C//D

I need to get the following array of strings when splitting:

A
/B
C
/D

I have tried the following code but it seems that simply splitting by ('/') will omit the occurrence of any '/' in the string.

mystring.split('/');

Is there a way that i can achieve this ?

Was it helpful?

Solution

Sure, you can use a regular expression. For example:

var input = "/A//B/C//D";
var result = Regex.Split(input, "(?<!/)/");

This will split the string by any / character not preceeded by another / character. Unfortunately, you will get an empty string for the first element of the result array. If this is a problem you can simply use a little bit of Linq to filter it out:

var result = Regex.Split(input, "(?<!/)/").Skip(1).ToArray();

Or

var result = Regex.Split(input, "(?<!/)/").Where(s => s.Length > 0).ToArray();

OTHER TIPS

Try this:

sArray = s.Replace("//", "~").Replace("/", "`").Replace("~", "`/").Split("`");

[Edit]

Or use a regex :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top