name
name

Reputation: 53

Split a string that contains "\"

I'm trying to split a string that represents a filepath, so the path contains pictures. For example should the pathstring #c:\users\common\pictures\2008 be converted to pictures\2008. The problem that I encounter is that when I use \ in a string it gives me an error. Sorry for the dumb question, m new with C#. This is what I've done so far:

string path = "#c:\users\common\pictures\2008";
string[] subs = path.Split('\');

int count = 0;
while(subs[count] != "pictures")
{
      count++;
}

string newPath = "";
for (int i = count; i < subs.Length; i++)
{
      newPath += "\" + subs[i]; 
}

Console.WriteLine(newPath);

Upvotes: 0

Views: 93

Answers (2)

Stefano Cavion
Stefano Cavion

Reputation: 741

That's because \ is a reserved char in C# so you must use it in this way '\\'

In case of string you can add before the special char @ In case of char you have to double it \\

See the documentation

string path = @"#c:\users\common\pictures\2008";
string[] subs = path.Split('\\');
  
int count = 0;
while (subs[count] != "pictures")
{
   count++;
}

string newPath = "";
for (int i = count; i < subs.Length; i++)
{
   newPath = Path.Combine(newPath ,subs[i]);
}

Console.WriteLine(newPath);

Also prefer the use, if possible, of Path.Combine since it take care of the escape char for you.

Upvotes: 4

Slugsie
Slugsie

Reputation: 905

Firstly, C# treats the '\' character as an escape character in a string, so you need to double it up to work.

string path = "#c:\\users\\common\\pictures\\2008";
string newPath = path.Substring(path.IndexOf("\\pictures\\") + 1);

What this does is take a substring of the 'path' starting at point after where "\pictures\" starts (because you don't want the initial '\').

Or this:

string path = "#c:\\users\\common\\pictures\\2008";
string[] subs = path.Split('\\');
int count = Array.IndexOf(subs, "pictures");
string newPath = String.Join("\\", subs, subs.Length - count);

Takes the path, splits into an array of the folders, finds the index of the element in the array that is 'pictures' and then joins the array starting at that point.

Upvotes: 2

Related Questions