5

When I read specific lines from a .txt file, I get a string like this one:

"Test,Test2,Test3,Test4,Test5,Test6"

I want to convert this string so it can fill a list, which looks like this:

List = [A, B, C, D, E, F]

Inserting values in such list can be done like this, for example:

["A", "B", "C", "D", "E", "F"]

But when I try to insert the string from the file, it ends up being stored only in the A variable, as the content is not being split. The other variables don't get the expected values.

What I'm getting:

List = ["Test,Test2,Test3,Test4,Test5,Test6", "B", "C", "D", "E", "F"]

What I want:

List = ["Test", "Test2", "Test3", "Test4", "Test5", "Test6"]

So basically I'm asking help with splitting a string to separate values by a certain char in Erlang!

Thanks for any help!

Victor Schröder
  • 6,738
  • 2
  • 42
  • 45
BorisMeister
  • 87
  • 1
  • 9
  • Basically only to insert it as it is for starters. Then i've tried to seperate it with the "," sign but no progress on that. – BorisMeister Dec 16 '13 at 21:04

1 Answers1

7

There are two built-in ways to split strings in erlang: string:tokens/2 and re:split/2,3.

For instance, using string:tokens:

Line = "Test,Test2,Test3,Test4,Test5,Test6",
[A, B, C, D, E, F] = string:tokens(Line, ",").

Using re:split:

Line = "Test,Test2,Test3,Test4,Test5,Test6",
[A, B, C, D, E, F] = re:split(Line, ",")
Soup d'Campbells
  • 2,333
  • 15
  • 14
  • This helped me out quite alot, thanks! What is the difference between the string:tokens and re:split? – BorisMeister Dec 16 '13 at 22:38
  • string:tokens uses a very basic string scanning mechanism, most likely just iterating over the contents of the list and comparing against the token(s). re, on the other hand, uses regular expressions, which allow for much greater complexity while still being fairly efficient (assuming your regex isn't self-mutilating). – Soup d'Campbells Dec 16 '13 at 22:51