-1

I have been prompted to write a program that removes every second letter the one issue I'm having is the fact that I'm required to use the modulus operator and the charAt method. I can think of different ways to do this but I'm not sure how to do it using the modulus operator in this instance. Could someone enlighten me?

javabeginner
  • 83
  • 1
  • 10

1 Answers1

0

You can do it as follows:

public class Main {
    public static void main(String[] args){
        String str="Schooled";
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<str.length();i++)
            if(i%2==0)
                sb.append(str.charAt(i));
        System.out.println(sb);
    }
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Wow, thank you. Although I haven't learned the class StringBuffer yet this code does work. It makes more sense to me now, thanks. – javabeginner Nov 12 '19 at 19:54
  • 1
    Prefer [`StringBuilder`](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) over `StringBuffer` (since *Java 5*!), also in the real world I would just `System.out.println("schooled".replaceAll("(.).", "$1"));` – Elliott Frisch Nov 12 '19 at 21:53