Delete last 4 characters in a string variable

189 visualizaciones (últimos 30 días)
Ryan
Ryan el 29 de Mzo. de 2011
Comentada: Eli Cuellar el 30 de En. de 2019
In my script, I have used the 'uigetfile' function to acquire the FileName and PathName of a .txt file in order to read it. Later in the script I need to parse that file and write the parsed information to another .txt file. I want to name the file I am writing to to a similar name as the file I'm reading from. Example:
Open/read from: C:\Documents and Settings\blah\TestFile.txt
Write/parsed to: C:\Documents and Settings\blah\TestFileParsed.txt
Basically how do I delete the last four characters in a string variable? Thanks for the help!

Respuesta aceptada

Matt Fig
Matt Fig el 29 de Mzo. de 2011
For example:
S = 'Mystringname.txt'
S = S(1:end-4)
  7 comentarios
Ian Mclennan
Ian Mclennan el 15 de Nov. de 2018
I love how you changed your picture after this whole discussion. Anyways, 7 years after this discussion ended you helped me out. Thank you.
Eli Cuellar
Eli Cuellar el 30 de En. de 2019
Just for the sake of correctness, the accepted answer is applicable to character vectors.
The answer would not work for an actual string, which is initialized using double quotes as opposed to the single quotes used to initialize character arrays. The following code will produce an error:
S = "Mystringname.txt"
S = S(1:end-4)
You can check the type of a variable using
class(my_variable)

Iniciar sesión para comentar.

Más respuestas (2)

Walter Roberson
Walter Roberson el 29 de Mzo. de 2011
Locating and removing the suffix:
idx = find(ismember(S,'./\:'),1,'last');
if S(idx) == '.'; S(idx:end) = []; end
The above includes protections against the possibility that the final component of the path does not include a '.'
If you are sure as sure as sure can be that the final component includes a '.', then
S(find(S=='.',1,'last'):end) = [];
  1 comentario
Alexei
Alexei el 30 de Jul. de 2014
Hi! I'm just curious to learn more about your suggestion. First, why did you include
'./\:'
in the string to compare S to, instead of just
'.'
?
Aren't we only interested in the period? It seems to me it should be
idx = find(ismember(S,'.'),1,'last');
Secondly, what is the benefit to using it this way of wrapping the find() function around the ismember() function, instead of using strfind() function?
Thanks

Iniciar sesión para comentar.


Steven Lord
Steven Lord el 15 de Nov. de 2018
If you just want to remove the extension, break the filename into its parts using fileparts.
  1 comentario
Walter Roberson
Walter Roberson el 16 de Nov. de 2018
fileparts is good because it does not assume that the extension is 3 characters long.

Iniciar sesión para comentar.

Categorías

Más información sobre Scope Variables and Generate Names en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by