How to delete last characters of a string
312 ビュー (過去 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 で Startup and Shutdown についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!