Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into a list with multiple values, using Erlang?

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!

like image 932
BorisMeister Avatar asked Dec 16 '13 20:12

BorisMeister


People also ask

How do I split a list in Erlang?

You can use lists:split/2 for this: divide(L, N) -> divide(L, N, []). divide([], _, Acc) -> lists:reverse(Acc); divide(L, N, Acc) when length(L) < N -> lists:reverse([L|Acc]); divide(L, N, Acc) -> {H,T} = lists:split(N, L), divide(T, N, [H|Acc]).

How do you split a string into a list of elements?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do I split a string into multiple parts?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.


1 Answers

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, ",")
like image 165
Soup d'Campbells Avatar answered Nov 15 '22 09:11

Soup d'Campbells