How to find the length of a string in Scala? String length() Method

Here, we are to learn about the length() method in Scala. The length() method finds the length of the string in Scala. We will see its working, syntax and examples.
Submitted by Shivang Yadav, on January 29, 2021

String is an immutable collection that stores sequences of characters.

How to find the length of the string in Scala?

We can find the length of a string in multiple ways. One can be by counting all characters till the end, i.e. till the "\0" is encountered. But Scala provides a direct method to get the length of a string which is the length() method.

String length() Method

The length() method in Scala is used to return the length of the given string. It returns an integer value which is the number of characters in the string.

Syntax:

string_name.length()

Parameters: The method is a parameter-less method, i.e. does not accept any parameter.

Return Value: It returns an integer which gives the length of the given string.

Example 1:

object myObject {
    def main(args: Array[String]) {
        val myString = "Learn Programming at includehelp"
        println("The string is '" + myString + "'")
        
        val stringLen = myString.length()
        println("The length of the string is " + stringLen)
    }
}

Output:

The string is 'Learn Programming at includehelp'
The length of the string is 32

Example 2:

object myObject {
    def main(args: Array[String]) {
        val myString = ""
        println("The string is '" + myString + "'")
        
        val stringLen = myString.length()
        println("The length of the string is " + stringLen)
    }
}

Output:

The string is ''
The length of the string is 0

Example 3: Print all character one by one using the length() method

object myObject {
    def main(args: Array[String]) {
        val myString = "scala"
        println("The string is '" + myString + "'")
        
        val stringLen = myString.length()
    
        println("Printing the string character by character : ")
        for(i <- 0 to (stringLen - 1) )
            println(myString.charAt(i))
    }
}

Output:

The string is 'scala'
Printing the string character by character : 
s
c
a
l
a



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.