Home »
Java programs
Java program to break a string into characters
In this article of java program, we will learn how to break a string into characters?
Submitted by Jyoti Singh, on October 07, 2017
Problem statement
Given a string and we have to break it into characters using Java.
Example
Input string: "Programming"
Output:
P r o g r a m m i n g
In this code we have one input:
- An int input (no. of test cases or more clearly the number of strings user wants to check (say 5 i.e user wants to check 5 strings and the program will continue for 5 inputs).
- A string input (It will be a string entered by the user which needs to be checked).
For each string we will have two outputs
Display the characters with a space
Java program to break a string into characters
Consider the program: It will take number of inputs, string and print characters.
import java.util.Scanner;
public class StringSubstrings {
public static void main(String[] args) {
Scanner Kb=new Scanner(System.in);
System.out.println("How man strings u want to break?");
//Take the input of no. of test cases
int t=Kb.nextInt();
//looping until the test cases are zero
while(t-->0){
//Input the string
System.out.println("Enter the string!");
String s=Kb.next();
//looping until the string length is zero
for(int i=0;i<s.length();i++){
//charAt function of string class get a particular character(specified by the index) from the string
char c=s.charAt(i);
//display each character one by one with a space
System.out.print(c+" ");
}
//to give a space of one line
System.out.println();
}
}
}