Reputation: 901
I have a string variable name
having value abcd.jpg
.
How can I remove the .jpg
from that string?
Upvotes: 0
Views: 8535
Reputation: 179
Since you are not asking for any kind of checking of the input, then you can simply use the end
feature of arrays in matlab to index backwards from the end of the array to ignore the last four elements as follows:
name = 'abcd.jpg' % original name
namewithoutfiletype = name(1:end-4) % name without the last four characters
Upvotes: 2
Reputation: 112659
For the general case (the file extension may have any number of characters, and the file name may contain dots):
>> name = 'example.file.html';
>> result = regexprep(name, '\.[^\.]*$', '')
result =
example.file
See regexprep
documentation or ask me if you're unsure how this works.
Upvotes: 2
Reputation: 1274
This should do it:
if(length(name) > 4)
if(name(length(name)-3:length(name)) == '.jpg')
name = name(1:length(name)-4);
end
end
Alternatively, if you want to look for any 3 character file extension at the end of a string, you could just check for a .
character at position length(name)-3
, like this:
if(name(length(name)-3) == '.')
name = name(1:length(name)-4);
end
You can also use the fileparts function as Daniel mentioned like this:
[~,name,~] = fileparts(name)
Upvotes: 2