简体   繁体   中英

Reverse a string to print only odd characters in java?

I know how to reverse a string in Java, code below (don't know if there could be some improvements, in any case feel free to let me know).

/**
 * Write a program that reverses a string in Java.
 *
 */

import java.util.Scanner;

 public class Test {
     public static void main(String[] args) {
         Scanner input = new Scanner(System.in);
         System.out.println("Please enter a string and I will reverse it.");
         String reverse = input.nextLine();

         for (int i = reverse.length() - 1; i >= 0; i--) {
             System.out.println(reverse.charAt(i));
         }
     }
 }

How can I tell this program to print only odd (and reversed) characters of that string? Thanks in advance.

Solution: subtract i by two.

/**
 * Write a program that reverses a string in Java.
 *
 */

import java.util.Scanner;

 public class Test {
     public static void main(String[] args) {
         Scanner input = new Scanner(System.in);
         System.out.println("Please enter a string and I will reverse it.");
         String reverse = input.nextLine();

         for (int i = reverse.length() - 1; i >= 0; i-=2) {
             System.out.println(reverse.charAt(i));
             if (i % 2 == 0) {
                 System.out.println(i);
             }
         }



     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM