user2837162
user2837162

Reputation:

Remove certain words from a string

hello i am using GetDirectory to get the directory for my program. Is there a way to split the following? AGM\Program\Python1\bin\Debugs\ is fixed.

C:\User\zhenhui\Desktop\AGM\Program\Python1\bin\Debug\

I want C:\User\zhenhui\Desktop\

C:\Users\zhenhui\Downloads\AGM\Program\Python1\bin\Debug\

I want C:\Users\zhenhui\Downloads\

C:\AGM\Program\Python1\bin\Debug\

I want C:\

D:\AGM\Program\Python1\bin\Debug\

I want D:\

E:\AGM\Program\Python1\bin\Debug\

I want E:\

Upvotes: 0

Views: 107

Answers (3)

Mark Hall
Mark Hall

Reputation: 54562

As I mentioned in my comment since you are trying to remove a fixed portion of your path you could use the String.Replace method. This is a simple Console Program to demonstrate, I created a Method to return the trimmed value, if it is used in an application that is a non console app you will need to remove the static operator.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(getProgramRootDirectory(@"C:\User\zhenhui\Desktop\AGM\Program\Python1\bin\Debug\"));
            Console.WriteLine(getProgramRootDirectory(@"C:\Users\zhenhui\Downloads\AGM\Program\Python1\bin\Debug\"));
            Console.WriteLine(getProgramRootDirectory(@"C:\AGM\Program\Python1\bin\Debug\"));
            Console.WriteLine(getProgramRootDirectory(@"D:\AGM\Program\Python1\bin\Debug\"));
            Console.WriteLine(getProgramRootDirectory(@"E:\AGM\Program\Python1\bin\Debug\"));
            Console.ReadLine();

        }
        static private string getProgramRootDirectory(string path)
        {
            return path.Replace(@"AGM\Program\Python1\bin\Debug\", "");
        }
    }
}

Upvotes: 0

chouaib
chouaib

Reputation: 2817

string directory = "C:\Users\zhenhui\Downloads\AGM\Program\Python1\bin\Debug\; //your path
int index = directory.indexOf("AGM");

string outString = directory.Substring(0, index);

Upvotes: 0

Konstantin
Konstantin

Reputation: 3294

directory.substring(0, directory.indexOf("AGM\\Program\\Python1\\bin\\Debugs\"))

Upvotes: 3

Related Questions