How would I return the last two characters of a string?
To get the last two characters of a string, call the slice() method, passing it -2 as a parameter. The slice method will return a new string containing the last two characters of the original string.
To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.
Explanation: The first character of given string is 'J' and the last character of given string is 'a'.
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)!
you can use
.takeRight(2)   var keyword="helloStackoverFlow"  println(keyword.takeRight(2)) // ow 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With