Saturday, November 23, 2013

Java String to Character array ( toCharArray() method )

Write a JAVA Program which accepts text of words seperated by commas and gives the output of words printed on seperated lines with commas removed.

Sample Input & Output:

Enter the string to parse
Monday,Tuesday,Wednesday,Thursday,Friday,Sunday

Monday
Tuesday
Wednesday
Thursday
Friday
Sunday

SOLUTION: 

 
import java.util.Scanner;

public class StringToCharArrayExample {
 public static void main(String[] args){
  
  //Creating Scanner object
  Scanner input = new Scanner(System.in);
  //Reading the input
  System.out.println("Please enter the text: ");
  String line = new String();
  //Converting to char array
  line=input.nextLine();
  char[] words = line.toCharArray();
  //Printing output
  for ( int i = 0; i < words.length; i++ ) {
   if(words[i]==',')
    System.out.println();
   else
    System.out.print(words[i]);
  }
 }
}

No comments:

Post a Comment