How to split string using scala? - string

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.

Related

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

Templates escaping in Kotlin multiline strings

If I want to use $ sign in multiline strings, how do I escape it?
val condition = """ ... $eq ... """
$eq is parsed as a reference to a variable. How to escape $, so that it will not be recognized as reference to variable? (Kotlin M13)
From the documentation
A raw string is delimited by a triple quote ("""), contains no
escaping and can contain newlines and any other character
You would need to use a standard string with newlines
" ...\n \$eq \n ... "
or you could use the literal representation
""" ... ${'$'}eq ... "
Funny, but that works:
val eq = "\$eq"
print("""... $eq ..."""") // just like you asked :D
Actually, if eq is a number (a price, or sth), then you probably want to calculate it separately, and an additional external calculation as I suggested won't hurt.
In the case where you know ahead of time what $-variables you want (like when querying Mongo, as it looks like you might be doing), you can create a little helper object that defines those variables. You also get some protection against accidentally misspelling one of your operators, which is neat.
object MongoString {
inline operator fun invoke(callback: MongoString.() -> String) = callback()
val eq = "\$eq"
val lt = "\$lt"
// ... and all the other operators ...
}
fun test() {
val query = MongoString { """{"foo": {$lt: 10}}""" }
}
I wrote simple versions for update and query strings for mongo here: https://gist.github.com/Yona-Appletree/29be816ca74a0d93cdf9e6f5e23dda15

Extracting Specific Strings From Text

I am trying to extract specific strings from my text. I have a string similar to this:
"blablabla(/)Hello Bob(|)bla(/)Hi(|)blablaba"
and I am trying to concatenate a string array of text between (/) and (|) but I cannot figure out a efficient way to do this. In this example I would want to return "Hello Bob" and "Hi". How can I effectively extract specific strings from a string in Swift?
Using a functional approach, you can:
split the string by (/), which returns an array of strings
for each element of the array, transform it into an array of strings split by (|)
filter the resulting array including only values (arrays) having more than one element
transform each element (array) of the resulting array into its first element
This is the code:
let array = string.componentsSeparatedByString("(/)")
.map { $0.componentsSeparatedByString("(|)") }
.filter { $0.count > 1 }
.map { $0[0] }
Given this input string:
let string = "blablabla(/)Hello Bob(|)bla(/)Hi(|)blablaba"
the result is:
["Hello Bob", "Hi"]

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

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]

How to manipulate Strings in Scala while using the Play framework?

I am using the play framework 2.2.1 and I have a question concerning the manipulation of Strings within view templates. Unfortunately I am not very familiar with the Scala programming language nor its APIs. The strings are contained in a List which is passed from the controller to the view and then I use a loop to process each string before they are added to the html. I would like to know how to do the following: trim, toLowerCase and remove spaces. As an example, if I have "My string ", I would like to produce "mystring". More specifically I would actually like to produce "myString", however I'm sure I can figure that out if someone points me in the right direction. Thanks.
UPDATE:
Fiaz provided a great solution, building on his answer and just for interest sake I came up with the following solution using recursion. This example is of course making many assumptions about the input provided.
#formatName(name: String) = #{
def inner(list: List[String], first: Boolean): String = {
if (!list.tail.isEmpty && first) list.head + inner(list.tail, false)
else if (!list.tail.isEmpty && !first) list.head.capitalize + inner(list.tail, false)
else if (list.tail.isEmpty && !first) list.head.capitalize
else list.head
}
if (!name.trim.isEmpty) inner(name.split(' ').map(_.toLowerCase).toList, true)
else ""
}
If you want to know how to do just the trimming, lower-casing and joining without spaces, try this perhaps?
// Given that s is your string
s.split(" ").map(_.toLowerCase).mkString
That splits a string into an array strings, splitting is done on one or more spaces so that gives you trimmed strings. You then map each element in the array with the function (x => x.toLowerCase) (for which the shorthand is (_.toLowerCase)) and then join the Array back into a single string using the mkString method that collections have.
So let's say you want to capitalize the first letter of the each of the space-split bits:
Scala provides a capitalize method on Strings, so you could use that:
s.split(" ").map(_.toLowerCase.capitalize).mkString
See http://www.scala-lang.org/api/current/scala/collection/immutable/StringOps.html
One suggestion as to how you can get the exact output (your example 'myString') you describe:
(s.split(" ").toList match {
case fst::rest => fst.toLowerCase :: rest.map(_.toLowerCase.capitalize)
case Nil => Nil }
).mkString
There is example of using the string manipulation below:
#stringFormat(value: String) = #{
value.replace("'", "\\'")
}
#optionStringFormat(description: Option[String]) = #{
if (description.isDefined) {
description.get.replace("'", "\\'").replace("\n", "").replace("\r", "")
} else {
""
}
}
#for(photo <- photos) {
<div id="photo" class="random" onclick="fadeInPhoto(#photo.id, '#photo.filename', '#stringFormat(photo.title)', '#optionStringFormat(photo.description)', '#byTags');">
This example obtained from https://github.com/joakim-ribier/play2-scala-gallery

Resources