Strings are stored as arrays of ASCII bytes in netCDF files. To read string data from netCDF files, use the STRING function to convert bytes back into characters. When writing an IDL string array to a variable, an extra dimension (the maximum string length) must be added to the variable definition. Both of these situations are illustrated by the following example:
string_in = REPLICATE('Test String',10,10)
;
Make a test string
string_in(0,0) = 'Long Test String' ; Make one element longer than the others.
HELP, string_in ;
IDL reports:
STRING_IN STRING = Array(10, 10)
ncdfid = NCDF_CREATE('string.nc', /CLOBBER)
;
Create a new netCDF file.
xid = NCDF_DIMDEF(ncdfid, 'height', 10)
;
Define first dimension.
yid = NCDF_DIMDEF(ncdfid, 'width', 10)
;
Define second dimension.
zid = NCDF_DIMDEF(ncdfid, 'length', MAX(STRLEN(string_in)))
;
Find the length of the longest string and use that as the third dimension.
id = NCDF_VARDEF(ncdfid, 'strings', [zid,yid,xid], /CHAR)
;
Define the variable with dimensions zid, yid, xid.
NCDF_CONTROL, ncdfid, /ENDEF ; Put the file into define mode.
NCDF_VARPUT, ncdfid, id, string_in ; Write the string variable. The array will be stored as bytes in the file.
NCDF_VARGET, ncdfid, id, byte_out ; Read the byte array back out.
NCDF_CLOSE, ncdfid ; Close the file.
HELP, byte_out ; IDL reports that BYTE_OUT is a (16, 10, 10) BYTE array.
PRINT, STRING(byte_out(*,0,0)) ; Taking the STRING of the first "row" of byte_out returns the first element of our original array, "Long Test String".
string_new = STRING(byte_out) ; Convert the entire byte array back into strings.
HELP, string_new ; The new string array has the same dimensions and values as our original string, string_in.
IF TOTAL(string_in NE string_new) EQ 0 THEN PRINT, 'Success!'
;
This statement compares the two arrays and prints "Success!" if they are equal--and they are.