Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing only the letters by ABC order from String

Tags:

java

I couldn't really explain myself in the title, what I meant is - get a String and check every letter and print it if the next char in the String is also the next letter in the ABC order, for example "almndrefg" will return "lmnefg", what I did so far is :

    package strings;

import java.util.Scanner;

public class P58Targil7 {
    public static Scanner in = new Scanner(System.in);

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String st2 = in.next();
        check(st2);
    }

    public static void check(String st1) {
        char sec,fir;
        for (int i = 0; i < st1.length() - 1; i++) {
            sec = st1.charAt(i + 1);
            fir = st1.charAt(i);
            sec--;
            if (fir == sec)
                System.out.print(fir);
        }
    }
}

What should I correct?

like image 658
DAVIDBALAS1 Avatar asked Nov 25 '15 12:11

DAVIDBALAS1


1 Answers

You got a small mistake, since you incremented sec instead of fir.

In addition, you must handle the printing of the second letter in each consecutive pair, and make sure each letter is only printed once.

    char sec,fir;
    boolean lastPrinted = false;
    for (int i = 0; i < st1.length() - 1; i++) {
        fir = st1.charAt(i);
        sec = st1.charAt(i + 1);
        if (fir + 1 == sec) {
            if (!lastPrinted) {
                System.out.print(fir);
            }
            System.out.print(sec);
            lastPrinted = true;
        } else {
            lastPrinted = false;
        }
    }
like image 115
Eran Avatar answered Oct 04 '22 03:10

Eran