How to delete last characters of a string
244 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Daniel Pollard
2020-12-17
What happens if you replace
name = "Motor 315S-4"
with
name = 'Motor 315S-4'
and try
name2 = name(1:end-2)?
5 个评论
Daniel Pollard
2020-12-17
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
2024-4-16
"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:
更多回答(1 个)
Malte Schmick
2024-4-16
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!