Splitting a string with delimiter - string

OK, So I'm having a string and want to split it and return its parts in a string array.
This is my code :
// import std.algorithm;
string include = "one,two,three";
string[] paths = splitter(include,",");
This throws an error : Error: cannot cast from Result to string[]
Even if I try adding a cast(string[]) in front of the function call.
Any ideas?

splitter returns a range which splits lazily.
To split eagerly, use split from std.array.
Alternatively, you can save the range to an array by using std.array.array, like this:
string[] paths = include.splitter(",").array();

Using split() from std.array might be more conventional in this case since it already deals with arrays and you wouldn't need to convert the type or anything, compared to splitter.
Requires:
import std.array;
Usage:
auto paths = split(include, ",");

Related

I can't get two String values in one string using templates

I got some function:
private fun selectHometown() = File("data/towns.txt")
.readText()
.split("\n")
.shuffled()
.first()
And if I try to get or print some string with the 2 values obtained from this function, the first value disappears. For example:
println("${selectHometown() ${selectHometown() }")
Will only print one city name, while I expect two. I guess the problem is related to string concatenation in Kotlin. Of course, I can get the desired result in a different way, but I'm wondering why this one doesn't work.
Windows way of terminating a line is to use "\r\n" so use it as delimiter :
private fun selectHometown() = File("data/towns.txt")
.readText()
.split("\r\n")
.shuffled()
.first()
println("${selectHometown()} ${selectHometown()}")

Getting all words out of a string

I have this arrayList that receives data dynamically from a database
val deviceNameList = arrayListOf<String>()
Getting the index 0 of the arraylist ie deviceNameList[0] prints a string of such a format:
[Peter, James]
How can i list all names in deviceNameList[0] individually.
Assuming your input string is [Peter, James], you could try removing the square brackets at both ends, then regex splitting on comma followed by optional whitespace.
String input = "[Peter, James]";
String[] names = input.substring(1, input.length()-1).split(",\\s*");
System.out.println(Arrays.toString(names));
This prints:
[Peter, James]
Note that Java itself places square brackets around the array contents in Arrays.toString. They are not part of the actual data.

Kotlin method chaining to process strings in a list

I have a list of strings I get as a result of splitting a string. I need to remove the surrounding quotes from the strings in the list. Using method chaining how can I achieve this? I tried the below, but doesn't work.Says type interference failed.
val splitCountries: List<String> = countries.split(",").forEach{it -> it.removeSurrounding("\"")}
forEach doesn't return the value you generate in it, it's really just a replacement for a for loop that performs the given action. What you need here is map:
val splitCountries: List<String> = countries.split(",").map { it.removeSurrounding("\"") }
Also, a single parameter in a lambda is implicitly named it, you only have to name it explicitly if you wish to change that.

Go how can i efficient split string into parts

i am fighting with a string splitting. I want to split string by wildcards into a slice, but this slice should contain this wildcards as well.
For example: /applications/{name}/tokens/{name} should be split into [/applications/ {name} /tokens/ {name}] etc.
Here is a sample code i wrote, but it is not working correctly, and i don't feel good about it either.
https://play.golang.org/p/VMOsJeaI4l
There are some example routes to be tested. Method splitPath split path into parts and display both: before and after.
Here is a solution:
var validPathRe = regexp.MustCompile("^(/{[[:alpha:]]+}|/[-_.[:alnum:]]+)+$")
var splitPathRe = regexp.MustCompile("({[[:alpha:]]+}|[-_.[:alnum:]]+)")
func splitPath(path string) parts{
var retPaths parts
if !validPathRe.MatchString(path) {
return retPaths
}
retPaths = splitPathRe.FindAllString(path, -1)
return retPaths
}
I made this by creating two regular expressions, one to check if the path was valid or not, the other to extract the various parts of the path and return them. If the path is not valid it will return an empty list. The return of this will look like this:
splitPath("/path/{to}/your/file.txt")
["path" "{to}" "your" "file.txt"]
This doesn't include the '/' character because you already know that all strings in the return but the last string is a directory and the last string is the file name. Because of the validity check you can assume this.

Convert a string to array in velocity

I have a velocity variable, like this:
$cur_record.getFieldValue("SelectRoles", $locale)
that is supposed to be an array. If I print its value, (just by putting $cur_record.getFieldValue("SelectRoles", $locale) in the code) i get:
["Accountant","Cashier"]
now, i want to iterate those 2 values, Accountant and Cashier, but it seems to be a String, not an Array, how can i convert that to an array so I can iterate it?..
I have tried to iterate it, but does not work, like this:
#foreach($bla_role in $cur_record.getFieldValue("SelectRoles", $locale))
$bla_role
#end
Also tried to get the value, as if it were an array, does not work either:
$cur_record.getFieldValue("SelectRoles", $locale).get(0)
I've tried setting it to another variable, like this:
#set($roleval = $cur_record.getFieldValue("SelectRoles", $locale))
$roleval.get(0)
but it does not work, but if i set a string, as the value is printed (the value hard coded), it does work!, like this:
#set($roleval = ["Accountant","Cashier"])
$roleval.get(0)
I dont know if I have to escape something, or I am missing something, can some one help me?
thank you!
You're trying to parse a String array that was previously serialized to String.
The following snippet uses substring, split and replace String methods to parse it.
#set($roleval = '["Accountant","Cashier"]')
#set($rolevalLengthMinusOne = $roleval.length() - 1)
#set($roles = $roleval.substring(1, $rolevalLengthMinusOne).split(","))
#foreach($role in $roles)
<h1>$role.replace('"',"")</h1>
#end
At first I tried to use #evaluate to parse it, but I ended up with these String methods.

Resources