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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.