How to return specific option type by splitting a string using scala? - string

I have a following string and I want to split it using scala
"myInfo": "name-name;model-model;number-10"
I want to split value of myInfo string such that I can access myName and its value seperately. e.g. myName:name, model:R210 etc
I am using following code to split string.
val data = (mainString \ "myInfo").as[String].split("\\;").map(_.split("\\-").toList)
.collect { case key :: value :: _ => key -> value }.toMap
It gives me desired result.
I am using
data.get("name"),data.get("model"),data.get("number")
to access list.
It gives me results in string type. While I want to get result of data.get("number") in integer format.
How do I get result of 'number' in integer format?

data.get("number").map(_.toInt)
will return an Option[Int]

Related

convert string to list of int in kotlin

I have a string = "1337" and I want to convert it to a list of Int, I tried to get every element in the string and convert it to Int like this string[0].toInt but I didn't get the number I get the Ascii value, I can do it with this Character.getNumericValue(number), How I do it without using a built it function? with good complexity?
What do you mean "without using a built in function"?
string[0].toInt gives you the ASCII value of the character because the fun get(index: Int) on String has a return type of Char, and a Char behaves closer to a Number than a String. "0".toInt() == 0 will yield true, but '0'.toInt() == 0 will yield false. The difference being the first one is a string and the second is a character.
A oneliner
string.split("").filterNot { it.isBlank() }.map { it.toInt() }
Explanation: split("") will take the string and give you a list of every character as a string, however, it will give you an empty string at the beginning, which is why we have filterNot { it.isBlank() }, we then can use map to transform every string in our list to Int
If you want something less functional and more imperative that doesn't make use of functions to convert there is this
val ints = mutableListOf<Int>() //make a list to store the values in
for (c: Char in "1234") { //go through all of the characters in the string
val numericValue = c - '0' //subtract the character '0' from the character we are looking at
ints.add(numericValue) //add the Int to the list
}
The reason why c - '0' works is because the ASCII values for the digits are all in numerical order starting with 0, and when we subtract one character from another, we get the difference between their ASCII values.
This will give you some funky results if you give it a string that doesn't have only digits in it, but it will not throw any exceptions.
As in Java and by converting Char to Int you get the ascii equivalence.
You can instead:
val values = "1337".map { it.toString().toInt() }
println(values[0]) // 1
println(values[1]) // 3
// ...
Maybe like this? No-digits are filtered out. The digits are then converted into integers:
val string = "1337"
val xs = string.filter{ it.isDigit() }.map{ it.digitToInt() }
Requires Kotlin 1.4.30 or higher and this option:
#OptIn(ExperimentalStdlibApi::class)

How to convert a variable to a raw string?

If I have a string, "foo; \n", I can turn this into a raw string with r"foo; \n". If I have a variable x = "foo; \n", how do I convert x into a raw string? I tried y = rf"{x}" but this did not work.
Motivation:
I have a python string variable, res. I compute res as
big_string = """foo; ${bar}"""
from string import Template
t = Template(big_string)
res = t.substitute(bar="baz")
As such, res is a variable. I'd like to convert this variable into a raw string. The reason is I am going to POST it as JSON, but I am getting json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 620 (char 619). Previously, when testing I fixed this by converting my string to a raw string with: x = r"""foo; baz""" (keeping in line with the example above). Now I am not dealing with a big raw string. I am dealing with a variable that is a JSON representation of a string where I have replaced a single variable, bar above, with a list for a query, and now I want to convert this string into a raw string (e.g. r"foo; baz", yes I realize this is not valid JSON).
Update: As per this question I need a raw string. The question and answer flagged in the comments as duplicate do not work (res.encode('unicode_escape')).

How to modify the value of a Hashmap, which has key&value as Strings,and the 'value' is a single string consisting of comma separated values

I am trying to modify a Hashmap .
The 'value' is a single string consisting of comma separated values.
(for e.g.: "aid=abc,bid=def,cid=gh2")
I need to replace particular values from them with a corresponding value from the DB.
(for e.g. changing the bid to 123, which would result in the above 'value' string as: "aid=abc,bid=123,cid=gh2")
And then set the modified 'value' to the corresponding key, so that the hashmap consists of modified values.
I tried to iterate through the keys , and with map(key) which will give the value, I tried to convert that to a list of comma separated values and then iterate through that list, and in each of the string, if I find 'bid'(example string above), then I do the necessary manipulation and then set it back to the Hashmap(which I Wasnt able to do since Strings arent mutable)
for (String name :outputMap.keySet())
List urlList = Arrays.asList(outputMap.get(name).split(",")); for(int i=0;i
expected result:"aid=abc,bid=123,cid=gh2" (post the manipulation)
actual result: unable to do.
I have used Stringbuffer for issues where string had to be modified, but was a little apprehensive to use that here, since this has already multiple conversions going.
The code needs to Java 7 compliant, since this is being deployed in a Client machine still using some legacy environment.(They are scheduled to migrate to java 8 , but thats scheduled for much later)
Any assistance here would be appreciated.
static Map<String, String> replace(Map<String, String> map, String toReplace, String replacement) {
return map.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey,
e -> transformValue(e.getValue(), toReplace, replacement)));
}
static String transformValue(String value, String toReplace, String replacement) {
return Arrays.stream(value.split(","))
.map(pair -> pair.split("="))
.map(sPair -> sPair[0] + "=" + (toReplace.equals(sPair[0]) ? replacement : sPair[1]))
.collect(Collectors.joining(","));
}
this will iterate through all entries of map and create a new map with changed values. Example:
var map = Map.of("key1", "aid=abc,bid=def,cid=gh2");
System.out.println(replace(map, "bid", "123").get("key1"));
will print aid=abc,bid=123,cid=gh2

How to split string using scala?

I have a following string and I want to split it using scala
"myInfo": "myName-name;model-R210;"
I want to split value of myInfo string such that I can access myName and its value seperately.
e.g. myName:name, model:R210 etc
I am using following code to split string -
(mainString \ "myInfo").as[String].split("\\;").toList.map(_.split("\\-"))
where mainString is Json and contains 'myInfo' key value pair.
How do I split string to seperate it by '-' and access it?
You can obtain a Map[String,String] like so:
val data: Map[String,String] = (mainString \ "myInfo").as[String]
.split("\\;").map(_.split("\\-").toList)
.collect {
case key :: value :: _ => key -> value
}.toMap
Then access your values:
val name = data.getOrElse("myName", "DefaultNameIfMissing")
First of all, shame on whoever encoded a complex data structure into a string in a JSON document; you shouldn't have to parse it at all. If it's under your control, I'd change that to something like
"myInfo": {
"myName": "name",
"model": "R210"
}
But if you can't change the input, then just do this to get the Map you want:
val myInfo = ((mainString \ "myInfo").as[String] split ';' map (_ split '-') collect { case Array(k,v) => k->v } ).toMap
No need to create Lists out of the intermediate results -- that would just slow things down. And just split on a Char, not a String (which would get compiled as a regular expression).
Note that the collect causes any component with no hyphen or more than one hyphen to be ignored; you might want to do something else there.

Understanding the string represented data type in Matlab

I have a String like '12,23,43,erogol,bla,3.4' and I want to parse it and see which type of values are in this string. For example if I give that string to function I expect to have a vector like output=["integer,integer,integer,string,string,double"] as the return of the function.
How could I do it in matlab ?
This can be done very easily using regular expressions.
input = '-12,12,0,erogol,bla,3.4,-3.4';
First replace the strings with 'string'.
Next catch the doubles
Finally catch the integers:
Example:
output = regexprep(input, '[a-zA-Z]*', 'string');
output = regexprep(output, '[-]*[0-9]*[.][0-9]*', 'double');
output = regexprep(output, '[-]*[0-9]*', 'integer');
Output now contains `integer,integer,integer,string,string,double,double'
Which you can split into a cell array using:
varTypes = regexp(output, ',', 'split');

Resources