1

Good evening all,

Probably a simple fix but I just cannot find it. I made this to print out every second chr from a string:

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string:");

    String input = sc.next();
    String total = "";

    for (int i = 0; i < input.length(); i += 2){
        total += input.charAt(i);
    }
    System.out.println(total);

It works like a charm, but the '+=' is highlighted and gives me the tip: string concatenation in loop. Am I using a wrong method to accomplish what I want?

MrEmper
  • 225
  • 1
  • 4
  • 18
  • 1
    You should use a `StringBuilder` instead. – Federico klez Culloca Feb 19 '18 at 18:29
  • Yes, string concat is a costly operation (in terms of performance) due to immutability of string. You should be using [StringBuilder](https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html). – Vasan Feb 19 '18 at 18:30
  • 1
    normally these types of hints are accompanied by alternatives or even refactoring options, are you sure you cannot simply do that? Or are you asking out of curiousity? – luk2302 Feb 19 '18 at 18:31

1 Answers1

3

You can use a StringBuilder instead:

StringBuilder total = new StringBuilder();

for (int i = 0; i < input.length(); i += 2){
    total.append(input.charAt(i));
}
System.out.println(total.toString());

See also:

http://www.pellegrino.link/2015/08/22/string-concatenation-with-java-8.html

lexicore
  • 42,748
  • 17
  • 132
  • 221