Category talk:Wren-str: Difference between revisions

→‎Source code: Added Str.splitCsv method.
m (→‎Source code: Added quotes to 'lang' attribute.)
(→‎Source code: Added Str.splitCsv method.)
Line 499:
return split.where { |e| !e.isEmpty }.toList
}
 
// Splits a CSV 'line' into a list of one or more strings separated by 'sep' which must be
// a single character (except \v). Deals properly with embedded separators in quoted fields.
// Removes leading and trailing quotes from quoted fields if 'dequote' is true.
static splitCsv(line, sep, dequote) {
if (!(line is String)) line = "%(line)"
if (!(sep is String) || sep.count != 1) {
Fiber.abort("Separator must be a single character string.")
}
if (!(dequote is Bool)) Fiber.abort("Dequote must be a boolean.")
var fields = line.split(sep)
var count = 0
var quoted = false
var chars = line.toList
for (i in 0...fields.count) {
var f = fields[i]
var fc = f.count
if (fc > 0) {
count = count + fc
if (!quoted && f[0] == "\"") {
if (f[-1] != "\"") {
quoted = true
chars[count] = "\v"
}
} else if (quoted && f[-1] == "\"") {
quoted = false
} else if (quoted) {
chars[count] = "\v"
}
} else if (quoted) {
chars[count] = "\v"
}
count = count + 1
}
fields = chars.join("").split(sep)
for (i in 0...fields.count) fields[i] = fields[i].replace("\v", sep)
if (dequote) {
for (i in 0...fields.count) {
var f = fields[i]
var fc = f.count
if (fc < 2) continue
if (f[0] == "\"" && f[-1] == "\"") fields[i] = f[1...-1]
}
}
return fields
}
 
// Convenience versions of the above method which use default parameters.
static splitCsv(line, sep) { splitCsv(line, sep, true) }
static splitCsv(line) { splitCsv(line, ",", true) }
 
// Splits a string 's' into two parts, before and after the first occurrence
9,476

edits