Borrar filtros
Borrar filtros

How to delete last characters of a string

244 visualizaciones (últimos 30 días)
Kasper Buchardt
Kasper Buchardt el 17 de Dic. de 2020
Comentada: Stephen23 el 16 de Abr. de 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)?

Respuesta aceptada

Daniel Pollard
Daniel Pollard el 17 de Dic. de 2020
What happens if you replace
name = "Motor 315S-4"
with
name = 'Motor 315S-4'
and try
name2 = name(1:end-2)?
Based off this previous answer.
  5 comentarios
Daniel Pollard
Daniel Pollard el 17 de Dic. de 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
Stephen23 el 16 de Abr. de 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 = "Motor 315S-4"
name{1}(end-1:end) = []
name = "Motor 315S"
How to access string arrays is explained in the MATLAB documentation:

Iniciar sesión para comentar.

Más respuestas (1)

Malte Schmick
Malte Schmick el 16 de Abr. de 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!

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by