How to delete last characters of a string
237 views (last 30 days)
Show older comments
Kasper Buchardt
on 17 Dec 2020
Commented: Stephen23
on 16 Apr 2024
I'm trying to delete the last characters from a string, here i try to delete "-4":
name = "Motor 315S-4"
name2 = name(1:end-2)
The above just returns "Name = 1x0 empty string array
Another method I've tried is to keep the first characters, here I try to keep "Motor 315"
name = "Motor 315S-4"
name2 = name(1:9)
But that results in error: "Index exceeds the number of array elements (1)
Are there other means of doing this?
These are the methods I've been able to find, and I need both functionalities. I use the strings for data presentation like:
display = name + " is tested " + testCount + " times";
As I understand I'm locked to a string because of this (character array not possible)?
0 Comments
Accepted Answer
Daniel Pollard
on 17 Dec 2020
What happens if you replace
name = "Motor 315S-4"
with
name = 'Motor 315S-4'
and try
name2 = name(1:end-2)?
5 Comments
Daniel Pollard
on 17 Dec 2020
Glad I could help, please accept the answer so that other users know that it worked.
I've done a bit of searching, and the only way that I can find to change a string (rather than char) is with strrep, which I don't think does what you're after. Maybe someone else could add to the discussion though.
Stephen23
on 16 Apr 2024
"But can it be true there is no way of doing the same with a string? All the answers I've found is for char"
name = "Motor 315S-4"
name{1}(end-1:end) = []
How to access string arrays is explained in the MATLAB documentation:
More Answers (1)
Malte Schmick
on 16 Apr 2024
Came across your question in my search for the same answer. For those similar to me, 4 years after the original post, here a working solution:
Matlab differentiates between strings and character vectors. It provides a lot of string-specific functions, two of which you can use here
strlength(String) and extractBefore(String,Pos)
For the above example, this command
name2=extractBefore(name,strlength(name))
would assign all but the last letter of string "name" to "name2", because 'extractBefore' ignores all characters after and including "Pos".
Hope that helps!
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!