Lee
Lee

Reputation: 31040

How do you remove whitespace in an Erlang string that has been assigned to a variable?

I am reading in data in the following format:

{ok,Volts} = file:open("voltage1.dat",read).

In the 'voltage.dat' file there is a single value which is converted into the string

" 9.9944639227844667e-001\n". This should be assigned to the Volts variable.

In order to use the string_to_float function later I need to strip away the spaces and remove the \n delimiter.

I have explored using string:strip, string:substr and re:replace library functions.

I am using the variable Volts as the input string when I try each of these, e.g:

string:substr(Volts,3,18).

This does not work. I think it is because of the way that I am inputting the Volts variable.

Can anyone put me right?

Upvotes: 0

Views: 524

Answers (2)

Vance Shipley
Vance Shipley

Reputation: 757

If you control the in[ut file format you can use file:consult/1 which will read in the terms directly.

Upvotes: 0

thanos
thanos

Reputation: 5858

{ok,Volts} = file:open("voltage1.dat",read).

will just open the file; Volts is a file descriptor, not the file's contents. In order to read the file you can use functions from the io module. Besides reading the whole file and then interpreting you can use fread/3:

1> {ok, V} = file:open("voltage.dat",read).
{ok,<0.34.0>}
2> io:fread(V,'',"~f").
{ok,[0.9994463922784467]}

If you don't want/can do that (maybe your file has a more complex format) remember that string are lists, therefore you can use filter/2 and other list functions

Upvotes: 3

Related Questions