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?

3
  • 1
    You should use a StringBuilder instead. Commented Feb 19, 2018 at 18:29
  • Yes, string concat is a costly operation (in terms of performance) due to immutability of string. You should be using StringBuilder. Commented Feb 19, 2018 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? Commented Feb 19, 2018 at 18:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

new StringBuilder((input.length()+1)/2), if you want to be more efficient (it preallocates the internal array, so it doesn't have to be resized).
could you please add explanation why it's more efficient? I suppose then answer be more helpful
Or, just print the chars directly to System.out.
@ADS The provided link explains this in full.
I see, thanks a lot!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.