0

I have create String list as follow

List("[MSC050,176484]", "[MSC050,176486]")

I try to convert this list into sub list as following code. I think it is way to achieve my task.

input.map(_.substring(5,13))

Then I got list as follow

List(50,17648, 50,17648)

I want to get list as follow

List(50176484, 50176486)

Can any one help on this?

3 Answers 3

1

I am guessing you meant this:

List(("MSC050",176484), ("MSC050",176486))

i.e a list of pairs of type (String, Int). If that's so, then the answer would be:

list.map(p => p._1.takeRight(3) + p._2)

_1 and _2 are the elements of the tuple. In this case _1 refers to the String and _2 refers to the Int

---Edit

Since you've clarified how the list looks like, then the answer would be:

list.map(_.foldLeft("")((newString, currentChar) => if(currentChar.isDigit) newString + currentChar else newString))

If what you are looking for is to preserve the digits only. FoldLeft traverses the String and at the same time it creates a new string, what I am basically telling it is that if the current char is a digit then add it to the new string, if not simply continue traversing the old string without modifying the new one.

Sign up to request clarification or add additional context in comments.

1 Comment

my list look like {List("[MSC050,176484]", "[MSC050,176486]")}
0

One way to do it is to simply remove all commas from your substring.

input.map(_.substring(5,13).replaceAll(",",""))
// res0: List[String] = List(5017648, 5017648)

1 Comment

Thank you given me valuable time to solve this problem
0

I'd go with a more generic approach like this:

import scala.util.matching
val pattern = raw"(\d+)".r
val result = List("[MSC050,176484]", "[MSC050,176486]").map(pattern.findAllIn(_).mkString("")).map(_.toLong)

It removes al the characters that are not digits and then convert the List[String] to a List[Long].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.