0

I am trying to figure out this substring feature and whether there exists a function call for it or not. As far as I can find, here and here along with various other places, there simply is no related function for this since strings are char arrays, and so they settled for only implementing the indexing feature.

MWE:

fileID = fopen('tryMe.env');
outDate = fgetl(fileID);

Where the file 'tryMe.env' only consists of 1 line like so:

2014/9/4

My wanted result is:

outDate = 
    '14/9/4'

I am trying to find a clean, smooth one liner to go with the variable definition of outDate, something along the lines of outDate = fgetl(fileID)(3:end);, and not several lines of code.

Thank you for your time!

4
  • This is possible, but I have to ask: Why can't you live with two lines? Commented Sep 24, 2014 at 6:13
  • stackoverflow.com/questions/3627107/… Commented Sep 24, 2014 at 6:17
  • I guess I am used to too much C, and simply cherish minimal but functional and readable code. I guess with the answer posted in Cheery's link, two lines solution is a bit more handsome. Thank you Commented Sep 24, 2014 at 6:25
  • try outDate = datestr( datenum ( fgetl( fopen('tryMe.txt') ) ) , 'yy/mm/dd') for a one liner ... but you still will have to close the file after, and i'm not sure about 'readability' on some one liners. Commented Sep 24, 2014 at 7:20

1 Answer 1

1

For the specific example you gave, seems like

outDate=textscan(fileID, '%*2c%infc')

would do what you want ( skip 2 characters, then read until end of line).

If you are trying to read a date, which you will later want to manipulate as a date, like comparing, differencing, etc, you could also use datenum on your fgetl line. Or, if you want a normalized date string, For instance

outDate=datestr(datenum(fgetl(fileID)),'yy/mm/dd')

would produce the string '14/09/04'

Sign up to request clarification or add additional context in comments.

1 Comment

Yes thank you, it would seem that your first example is what I was looking for since I need to handle the input as nothing but strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.