Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Get last two characters from string

Tags:

string

scala

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

like image 705
jahilldev Avatar asked Jun 12 '12 10:06

jahilldev


People also ask

How do I get 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.

How do I get the last character of a 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.

What is the default last element of a string?

Explanation: The first character of given string is 'J' and the last character of given string is 'a'.


2 Answers

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)!

like image 157
oxbow_lakes Avatar answered Oct 08 '22 07:10

oxbow_lakes


you can use

.takeRight(2) 

var keyword="helloStackoverFlow"  println(keyword.takeRight(2)) // ow 
like image 35
Govind Singh Avatar answered Oct 08 '22 07:10

Govind Singh