Scala - Get last two characters from string

StringScala

String Problem Overview


How would I return the last two characters of a string?

String Solutions


Solution 1 - String

Scala allows you to do this in a much cleaner way than the standard String API by leveraging the collections API (for which there is an implicit conversion from a java.lang.String into an IndexedSeq[Char]):

str takeRight 2

The fantastic thing about the API of course, is that it preserves the type representation of the original "collection" (i.e. String in this case)!

Solution 2 - String

you can use

.takeRight(2)

var keyword="helloStackoverFlow"

println(keyword.takeRight(2)) // ow

Solution 3 - String

You can take (string length -1) that reveal last index of your string, (string length -2) will be next character from end:

str(str.length-1)+str(str.length-1)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjahilldevView Question on Stackoverflow
Solution 1 - Stringoxbow_lakesView Answer on Stackoverflow
Solution 2 - StringGovind SinghView Answer on Stackoverflow
Solution 3 - StringDinar GataullinView Answer on Stackoverflow