Write a java program to display alternate character from a given string. | EasyCoding45

Write a Java program to display alternate characters from a given string.


Certainly! Here's a simple Java program that displays alternate characters from a given string:

Program : (Write a java program to display alternate character from a given string.)


import java.util.Scanner; public class AlternateCharacters { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input string from the user System.out.print("Enter a string: "); String inputString = scanner.nextLine(); // Displaying alternate characters System.out.print("Alternate characters: "); displayAlternateCharacters(inputString); scanner.close(); } private static void displayAlternateCharacters(String input) { for (int i = 0; i < input.length(); i += 2) { char ch = input.charAt(i); System.out.print(ch); } System.out.println(); // Move to the next line for better formatting } }

Note: This program takes a string as input and then uses the displayAlternateCharacters method to iterate through the string and print every alternate character. The for loop starts from the first character (index 0) and increments the index by 2 in each iteration.

You can copy and paste this code into a Java file (e.g., AlternateCharacters.java) and then compile and run it using a Java compiler.


Output :

https://easycoding45.blogspot.com/2023/12/write-java-program-to-display-alternate.html


Comments