MATLAB Answers

0

take part from string

Asked by Khaldon Soued on 20 Mar 2018
Latest activity Commented on by Walter Roberson
on 12 Aug 2018 at 20:36
Accepted Answer by Jan

hello, how could I take part from string for ex. I have this path : C:\Users\khs\Desktop\pics\photos and want matlab to make it C:\Users\khs\Desktop\pics\ futhermore want it to take the name of folder ( khs ) please help me thanks

Tags

No tags entered yet.

1 Answer

Answer by Jan
on 20 Mar 2018
Edited by Jan
on 20 Mar 2018
 Accepted Answer

S = 'C:\Users\khs\Desktop\pics\photos';
[PathName, Folder] = fileparts(S);

Or more flexible:

S = 'C:\Users\khs\Desktop\pics\photos';
C = strsplit(S, '\');
PathName = sprintf('%s\\', C{1:end-1});
PathName(end) = [];
Folder   = C{end};

  3 Comments

perfekt danke sehr .. thank you so much :)

one more question please how to change cell array to cells

Jan
on 20 Mar 2018

The question is not clear: "cells" is just a different name for "cell array". So what do you want to "change" exactly?

Walter Roberson
on 12 Aug 2018 at 20:36

Be cautious in generalizing the "more flexible" code for use with Linux or Mac. The obvious approach is to use something like

C = strsplit(regexprep(S, '\\', '/'), '/')

which changes all \ characters to /: this produces valid MS Windows paths because MS Windows permits both \ and / as the path separator. The problem encountered is that \ is a valid character in Linux and Mac filenames, so a file name such as 'hi\tlo' is a valid 6-character file name (just not a great one, as people would tend to think the \t was a tab character.) The replaced version would be 'hi/tlo' which would not refer to the same place at all even if it existed.

Thus, the generalized version would have to only translate \ to / if ispc() is true

Sign in to comment.