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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With