String Manipulation

183 views (last 30 days)
Mohamed Yaseen
Mohamed Yaseen on 25 Jan 2011
Commented: Jérôme on 18 Aug 2022
Hi All,
For example, I have filename called abcdefhijklm.xlsx and this file is displayed on the GUI. I wanted to remove the extension in the file name 'xlsx' and display only 'abcdefhijklm'. How can i manipulate this string.
Thanks in Advance Yaseen.

Accepted Answer

Andreas Goser
Andreas Goser on 25 Jan 2011
I see two approaches. As you have a filename, you can have MATLAB take care of this by using the FILEPARTS command:
[pathstr, name, ext] = fileparts('abcdefhijklm.xlsx')
There is a generic approach for string search and string manipulation using commands like REGEXP, STRFIND and many others. Here, you would need to define the search logic yourself like "find all dots in the character array, identify the last dot and return all characters before that dot".
  3 Comments
Qi Hao Goh
Qi Hao Goh on 12 May 2011
sorry to interrupt, if we were to use regexp to find the dot in the filename, how do we do that?
Walter Roberson
Walter Roberson on 12 May 2011
Please start a new Question for this topic.

Sign in to comment.

More Answers (1)

Jérôme
Jérôme on 18 Aug 2022
Since R2016b, you can also use extractBefore.
filename_with_extension = "abcdefhijklm.xlsx";
filename_without_extension = extractBefore(filename_with_extension, ".")
filename_without_extension = "abcdefhijklm"
  2 Comments
Rik
Rik on 18 Aug 2022
This is risky advice. The fileparts function is designed to separate the path, file name, and extension. I don't know what edge cases there are, but let me try the first one that comes to mind:
filename_with_extension = "filename_with_a.dot_in_it.xlsx";
filename_without_extension = extractBefore(filename_with_extension, ".")
filename_without_extension = "filename_with_a"
Exceptions like this is why it is safer to stick to functions that have been debugged for two decades by Mathworks.
Jérôme
Jérôme on 18 Aug 2022
I totally agree with you, to be sure of the result regardless of the filename content, fileparts is the way to go.
I just wanted to mention this option if we know the filename content won't cause any issue, and because we can use directly the filename without extension, which in some cases can save us an intermediate line of code (I am not saying this is the thing to do, I just wanted to mention that this possibility exists).
filename_with_extension = "abcdefhijklm.xlsx";
% Display filename in one line
disp(extractBefore(filename_with_extension, "."))
abcdefhijklm
% Display filename in two lines
[pathstr, name, ext] = fileparts(filename_with_extension);
disp(name)
abcdefhijklm

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!