Scala String compareTo() method with example
The compareTo() method is utilized to compare a string with another string.
Some points to remember:
- Here, If a string(S1) is same as string(S2) in comparison then this method returns zero.
- If S1 is less than S2 then a negative number is returned which is the difference of character value.
- If S1 is greater than S2 then a positive number is returned.
Method Definition: int compareTo(String another String)
Return Type: It returns an integer.
Example #1:
object GfG
{
def main(args : Array[String])
{
val m 1 = "Nidhi"
val result = m 1 .compareTo( "Nidhi" )
println(result)
}
}
|
It returns zero as both the strings are same.
Example #2:
object GfG
{
def main(args : Array[String])
{
val m 1 = "Nidhi"
val result = m 1 .compareTo( "Nidh" )
println(result)
}
}
|
It returns a positive number as S1 is greater than S2 here.
Example #3:
object GfG
{
def main(args : Array[String])
{
val m 1 = "Nidhi"
val result = m 1 .compareTo( "nidh" )
println(result)
}
}
|
It returns a negative number as S1 is less than S2 here.
Last Updated :
03 Oct, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...