In Matlab, I have a string containing a path to a file:

path = 'C:/Data/Matlab/Dir/file.m'

I want now want to extract the 'Dir' part of the string. One way to do this is:

[first, second, third, fourth, fifth] = strtok(path, '/')

And then take the fourth element, and finally remove the first character from it (the /).

I'm just wondering if there is a more elegant solution? It seems a little cumbersome to have to explicitly store all the first ... fifth elements and then manually remove the /.

Thanks.

有帮助吗?

解决方案 3

Try:

parts = strsplit(path, '/');
DirPart = parts{end-1};

其他提示

you can try the fileparts function as follow:

[ParentFolderPath] = fileparts('C:/Data/Matlab/Dir/file.m');
[~, ParentFolderName] = fileparts(ParentFolderPath) ;
ParentFolderName = 'Dir'
parts = strsplit(file_path, filesep);
parent_path = strjoin(parts(1:end-1), filesep);

Try

s = regexp(path, '/', 'split')
s(4)

as described here at "Split String at Delimiter using split Keyword".

If you don't want to care about the number of elements of your path, and you don't want to use strsplit, which is not available in older versions of Matlab, you can also use this one liner:

directory = getfield( fliplr(regexp(fileparts(path),'/','split')), {1} )

%% or:
% alldir = regexp(fileparts(path),'/','split')
% directory = alldir(end)

which will always return the parent folder of the specified file.

You should also consider using filesep instead of '/' to get better compatibility with various systems.

Max solution is good for windows, but might fail on linux/mac due to the slash at the beginning of absolute paths. My suggestion would be:

parts = strsplit(path, filesep);
DirPart = parts{end-1};
if path(1) == filesep
    DirPart = [filesep,DirPart];
end
if path(end) == filesep
    DirPart = [DirPart,filesep];
end

find the parent directory with a single line of code if you don't know how many folders are layering

fliplr(strtok(fliplr(pname),'\'))

there is also the good old way...

n=size(path,2);

while path(n)~='/'; n=n-1; end

i=n-2;

while path(i)~='/'; i=i-1; end

% result
path(i+1:n-1)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top