SCALA: change the separator in Array - arrays

I have an Array like this.
scala> var x=Array("a","x,y","b")
x: Array[String] = Array(a, x,y, b)
How do I change the separator comma in array to a :. And finally convert it to string like this.
String = "a:x,y:b"
My aim is to change the comma(separators only) to other separator(say,:), so that i can ignore the comma inside second element i.e, x,y. and later split the string using : as a delimiter

Your question is unclear, but I'll take a shot.
To go from:
val x = Array("a","x,y","b")
to
"a:x,y:b"
You can use mkString:
x.mkString(":")

Related

Groovy Convert string data to map

I have a large String which I want to convert to a Map in groovy.
The String data is an array of key value pairs each key and value is enclosed in square brackets [] and separated by commas. Full data string here: https://pastebin.com/raw/4rBWRzMs
Some of the values can be empty e.g. '[]' or a list of values containing , and : characters e.g.
[1BLL:220,1BLE:641,2BLL:871,2BLE:475,SW:10029,KL:0,KD:78,ODT:148,AVB:358]
I only want to split on these characters if they are not enclosed in square brackets [].
The code I have tried but breaks when there are a list of values. Is there a better way? Thanks.
String testData="[[DEVICE_PROVISIONED]: [1], [aaudio.hw_burst_min_usec]: [2000],[debug.hwui.use_buffer_age]: [false], [ro.boot.boottime][1BLL:220,1BLE:641,2BLL:871,2BLE:475,SW:10029,KL:0,KD:78,ODT:148,AVB:358], ro.boot.hardware]: [walleye],[dev.mnt.blk.postinstall]: [],[ro.boot.usbradioflag]: [0], [ro.boot.vbmeta.avb_version]: [1.0], [ro.boot.vbmeta.device]: [/dev/sda18], [ro.boot.vbmeta.device_state]: [unlocked]]"
def map = [:]
testData.replaceAll('\\[]','null').replaceAll("\\s","").replaceAll('\\[','').replaceAll(']','').split(",").each {param ->
def nameAndValue = param.split(":")
map[nameAndValue[0]] = nameAndValue[1]
}
I'd grep the key-value-tuples from that format and build a map from
there. Once this is done it's easier to deal with further
transformations. E.g.
def testData="[DEVICE_PROVISIONED]: [1], [aaudio.hw_burst_min_usec]: [2000],[debug.hwui.use_buffer_age]: [false], [ro.boot.boottime]: [1BLL:220,1BLE:641,2BLL:871,2BLE:475,SW:10029,KL:0,KD:78,ODT:148,AVB:358], [ro.boot.hardware]: [walleye],[dev.mnt.blk.postinstall]: [],[ro.boot.usbradioflag]: [0], [ro.boot.vbmeta.avb_version]: [1.0], [ro.boot.vbmeta.device]: [/dev/sda18], [ro.boot.vbmeta.device_state]: [unlocked]"
def map = [:]
(testData =~ /\s*\[(.*?)\]\s*:\s*\[(.*?)\]\s*,?\s*/).findAll{ _, k, v ->
map.put(k,v)
}
println map.inspect()
// → ['DEVICE_PROVISIONED':'1', 'aaudio.hw_burst_min_usec':'2000', 'debug.hwui.use_buffer_age':'false', 'ro.boot.boottime':'1BLL:220,1BLE:641,2BLL:871,2BLE:475,SW:10029,KL:0,KD:78,ODT:148,AVB:358', 'ro.boot.hardware':'walleye', 'dev.mnt.blk.postinstall':'', 'ro.boot.usbradioflag':'0', 'ro.boot.vbmeta.avb_version':'1.0', 'ro.boot.vbmeta.device':'/dev/sda18', 'ro.boot.vbmeta.device_state':'unlocked']
Note that I have fixed some syntax in the testData and removed the outer
[]. If the original testData are actually containing invalid syntax
to the rules given, then this will not work.

String.init(stringInterpolation:) with an array of strings

I was reading over some resources about Swift 5's String Interpolation and was trying it out in a Playground. I successfully combined two separate Strings but I am confused about how to combine an Array of Strings.
Here's what I did ...
String(stringInterpolation: {
let name = String()
var combo = String.StringInterpolation(literalCapacity: 7, interpolationCount: 1)
combo.appendLiteral("Sting One, ")
combo.appendInterpolation(name)
combo.appendLiteral("String Two")
print(combo)
return combo
}())
How would you do something like this with an Array of Strings?
It’s unclear what this is supposed to have to do with interpolation. Perhaps there’s a misunderstanding of what string interpolation is? If the goal is to join an array of strings into a single comma-separated string, just go ahead and join the array of strings into a single string:
let arr = ["Manny", "Moe", "Jack"]
let s = arr.joined(separator: ", ")
s // "Manny, Moe, Jack”
If the point is that the array element type is unknown but is string-representable, map thru String(describing:) as you go:
let arr = [1,2,3]
let s = arr.map{String(describing:$0)}.joined(separator: ", ")
s // "1, 2, 3”

Appending All Entries in array to string?

I currently have an array containing x amount of strings and am looking to append all of these entries to a string in OCaml.
I know that the way to append a string to another in OCaml is by using
let a ="Hello"
let b= "Blah Blah " ^ a
However I would like to do this using all entries in my array. Then continue the string after appending the full array. Something similar to this:
let myArray = Array.make stages "Some text"
let myString = "I'm looking to append "^(ALL ENTRIES IN ARRAY)^" to this string"
If you had a list of strings rather than array then String.concat will do the trick. So if you have array you could convert the array to list and then apply String.concat as in:
String.concat " " (Array.to_list str_arr)
But if you don't want to convert it to a list you could use fold_left as in:
Array.fold_left (fun x y -> x ^ y ^ " ") "" str_arr
Notice that fold_left appends a space to every string in the array including the last one. String.concat is better; it uses the filler only between the strings

Data types not reading correctly when reading text file in Scala

I'm reading a tab delimited text file into an array using the following code:
val vars = io.Source.fromFile(filename).getLines.toArray.map(_.split('\11'))
What I end up with is Array[Array[String]] = Array(Array(a,b,c,d), Array(e,f,g,h))
Each element in the arrays are strings, but they aren't enclosed by quotes so when I try something like vars.indexOf(a) I get an error because Scala doesn't know what 'a' is. Scala seems to think a is a variable name which hasn't been defined.
Is there a way to make the elements of the arrays be enclosed in quotes as strings or is there some other way to reference the element of the array so Scala knows what it is looking for?
I'm VERY new at Scala so hopefully the solution is simple.
Thanks.
You have an Array[Array[String]], you can map and get back an array of indexes:
scala> Array(Array("a", "b", "c", "d"), Array("e", "f", "g", "h"))
res0: Array[Array[String]] = Array(Array(a, b, c, d), Array(e, f, g, h))
scala> res0.indexOf("a")
res1: Int = -1
scala> res0.map(_.indexOf("a"))
res2: Array[Int] = Array(0, -1)
Also note that you get an error probably because you wrote indexOf(a) instead of indexOf("a"), even if what you see are letters not wrapped by double quotes, they are still strings.
You can then also know the array position using zipWithIndex and filter:
scala> res0.map(_.indexOf("g")).zipWithIndex.filter(_._1 != -1)
res3: Array[(Int, Int)] = Array((2,1))
Where the first number in the tuple is the string index position and the second the array which contains the string.
indexOf(a) will fail in Scala for the same reason as any other language - because a is an undefined variable. You want indexOf("a"). Secondly vars.indexOf("a") won't work because vars is of type Array[Array[String]] and so cannot contain "a" - it contains Array[String].
Suggest providing more code so we may be able to help more with what your trying to do.

Storing multiple values from one text field into an array

I have one text field but I want to be able to store the multiple values entered in that text field (eg. 1,2,3,4) stored into an array. So far, all it does is store it all as one element that still has the commas. How can I get rid of the commas and store each value separately?
You can use global split function which works on any Sequence (including String):
If you want it to be separated by commas only:
let array = split("x,y,z") { $0 == "," }
If you'd want to separate by either commas or spaces:
let array = split("x, y z") { contains(", ", $0) }
You can use the string method componentsSeparatedByString(separator: String) -> [String]
For example:
let example = "1,2,3,4"
let elements = textfieldValue.componentsSeparatedByString(",") // elements is an array with Strings.
Just try below :-
NSArray *valueArr=[[yourTextfield stringValue] componentsSeparatedByString:#","];

Resources