Dena
Dena

Reputation: 43

extract information from a path

if I have this path A/B//C I want to extract A,B,C I was thinking about store index of /,// and extract the values based on the indexes but this create a problem for me since // does not have a single index

/ -- index(1)
/ -- index(3)
/ -- index(4) 


    for (int index = 0; index <= path.Length; index++)
    {
            if (path[index] == '/')
            {
                pathIndex[index] = index;
                pathChar[index] = "/";
                Console.WriteLine("Index {0} char{1}", pathIndex[index], pathChar[index]);

            }              

    }

but if there is another way which would be shortest and better. I want to know any effort will be strongly appreciated

Upvotes: 0

Views: 137

Answers (2)

Homam
Homam

Reputation: 23841

I prefer to use the Path.DirectorySeparatorChar instead of '/' for splitting:

string currentDirectory = Directory.GetCurrentDirectory();

string[] parts = currentDirectory.Split(Path.DirectorySeparatorChar);

foreach (var item in parts)
    Console.WriteLine("{0}: {1}", currentDirectory.IndexOf(item), item);

Good luck!

Upvotes: 1

sisve
sisve

Reputation: 19781

var input = "A/B//C";
var splitted = input.Split(new[] { '/' });
for (var idx = 0; idx < splitted.Length; ++idx)
    Console.WriteLine("Index={0} Value={1}", idx, splitted[idx]);

If you dont want empty values inside splitted, pass StringSplitOptions.RemoveEmptyEntries to String.Split.

Upvotes: 2

Related Questions