Cut and re-join strings
2 次查看(过去 30 天)
显示 更早的评论
Hello, I am trying to create a function that will cut a section out of a string and join the two remaining parts togather.
I am getting some weird results towards the end
here is my code
pat = 'MATLAB';
cliplength = length(pat);
stringinput = 'D:\Documents and Settings\212068586\My Documents\MATLAB\help'
endpoint = regexp(stringinput, pat);
newstringstart = [];
newstringtail = [];
for w = 1:length(stringinput)
if w < endpoint
newstringstart(w) = stringinput(w);
end
end
if (((endpoint + cliplength) < w) && (w > endpoint))
for h = (endpoint + cliplength):length(stringinput)
newstringtail(h) = stringinput(w);
end
%newstring(w) = stringinput(w - (endpoint + cliplength));
end
disp(char(strcat(newstringstart, newstringtail)))
Any ideas why it isn't working?
Thanks
Bill
0 个评论
采纳的回答
Matt Fig
2011-6-21
Rather than using a verbal description, show us what you want. For example, if you start with these:
pat = 'MATLAB';
stringinput = 'D:\Documents and Settings\212068586\My Documents\MATLAB\help'
what do you want to have at the end?
12 个评论
Matt Fig
2011-6-21
I just tried it in Windows 7 and you are correct in at least one sense. I pasted:
C:/Users/matt fig/Desktop/General
into the location bar of an open folder and was taken to the correct location. However, the OS immediately changed the location to:
C:\Users\matt fig\Desktop\General
So I wonder if an inquiry from MATLAB would ever really return a string with / in it?
Walter Roberson
2011-6-21
Yes, some inquiries from MATLAB return or directory names as passed in to MATLAB rather than canonicalizing the paths.
I do not know if cd() or uigetdir() on Windows could ever be convinced to return a \ delimited name. Possibly so, see the last paragraph or so of the below-referenced blog.
This state of accepting / or \ has been part of Windows from the beginning: it dates right back to the introduction of directories in DOS. See the following blog from a Microsoft Employee: http://blogs.msdn.com/b/larryosterman/archive/2005/06/24/432386.aspx
更多回答(1 个)
Fangjun Jiang
2011-6-21
Bill, What type of task are you dealing with? I suggest you changing your mind set a little bit. Based on the description part of your question, would this solve your problem? Try not to think of the string at one letter a time.
strrep(stringinput,'MATLAB','')
2 个评论
Fangjun Jiang
2011-6-21
If you need to deal with the full path of a file or directory, then using related function makes more sense then processing it as ordinary string. Use the following functions:
[PathStr]=fileparts(stringinput)
and you repeat it again and again
fileparts(PathStr)
Other functions are:
fullfile()
exist(PathStr,'file')
exist(PathStr,'dir')
which(Path)
pwd
cd
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Scope Variables and Generate Names 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!