Home »
Scala
Scala String length() Method
By IncludeHelp Last updated : October 20, 2024
Description and Usage
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
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