In this article, we will understand how to iterate through each character of the string. String is a datatype that contains one or more characters and is enclosed in double quotes (“ ”). Char is a datatype that contains an alphabet or an integer or a special character.
Below is a demonstration of the same −
Suppose our input is −
The string is defined as: Java Program
The desired output would be −
The characters in the string are: J, a, v, a, , P, r, o, g, r, a, m,
Algorithm
Step 1 - START Step 2 - Declare a string namely input_string, a char namely temp. Step 3 - Define the values. Step 4 - Iterate over the string, print each character at index ‘i’ of the string along with a blank space. Step 5 - Display the result Step 6 - Stop
Example 1
Here, for-loop.
public class Characters { public static void main(String[] args) { String input_string = "Java Program"; System.out.println("The string is defined as: " +input_string); System.out.println("The characters in the string are: "); for(int i = 0; i<input_string.length(); i++) { char temp = input_string.charAt(i); System.out.print(temp + ", "); } } }
Output
The string is defined as: Java Program The characters in the string are: J, a, v, a, , P, r, o, g, r, a, m,
Example 2
Here, for-each loop.
public class Main { public static void main(String[] args) { String input_string = "Java Program"; System.out.println("The string is defined as: " +input_string); System.out.println("The characters in the string are: "); for(char temp : input_string.toCharArray()) { System.out.print(temp + ", "); } } }
Output
The string is defined as: Java Program The characters in the string are: J, a, v, a, , P, r, o, g, r, a, m,