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!
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]).
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.
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.
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, ",")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With