Scala String charAt() Method with Example

Here, we will learn about the charAt() method in Scala. The charAt() method is used to return the character and the given index. 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.

String charAt() Method

The charAt() method is used to get the character from the string at a given index.

Syntax:

string_Name.charAt(index)

Parameters: The method accepts a single parameter which is the index of the character to be found.

Return Value: It returns a character which is found at the given index.

Example 1: Program to illustrate the working of charAt() method

object myObject {
    def main(args: Array[String]) {
        val myString = "scala"
    
        println("The string is '" + myString + "'")
    
        println("Character at index 4 is " + myString.charAt(4))
    }
}

Output:

The string is 'scala'
Character at index 4 is a

Example 2: Program to print characters of string

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.