Scala program to convert the string into a character array

Here, we are going to learn how to convert the string into a character array in Scala programming language?
Submitted by Nidhi, on May 22, 2021 [Last updated : March 10, 2023]

Scala – Convert String to Char Array

Here, we will create a string and a character array and then we will convert the string into a character array using the toCharArray() method and then print the character array on the console screen.

Scala code to convert the string to character array

The source code to convert the string into a character array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to convert string into
// character array

object Sample {
  def main(args: Array[String]) {
    var str = "ABCDEF";
    var charArr = Array[Char](6)

    var i: Int = 0;

    charArr = str.toCharArray();

    println("Character array: ");
    while (i < charArr.length) {
      printf("%c ", charArr(i));
      i = i + 1;
    }
    println();
  }
}

Output

Character array: 
A B C D E F

Explanation

In the above program, we used an object-oriented approach to create the program. And, we created an object Sample. Here, we defined main() function. The main() function is the entry point for the program.

In the main() function, we created a string str and a character array charArr. And, we used the toCharArray() method to convert the string into a character array. After that, we printed the character array on the console screen.

Scala String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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