2

I would like to format strings which contains codes like:

 "function() { for(i=0;i<n;i++){ return i; }}"

The point is to put new lines to each ; except in the for loop, so the formatted output should be something like this:

function() {
   for(i=0;i<n;i++){
    return i;
  } 
 } 

Is there any written function for this, or I have to loop through the whole string?

2
  • jsbeautifier.org Commented Dec 4, 2017 at 13:17
  • 1
    IDE eclipse > format ? Also, you are also adding a new line after { and } in your sample... Please provide a minimal reproducible example Commented Dec 4, 2017 at 13:26

1 Answer 1

3

You have to use google-java-format-1.5.jar and google-java-format-1.5-all-deps.jar

and see the below example code

public class Main {
   public static void main(String[] args) {
      Formatter formatter = new Formatter();
      try {
        System.out.println(formatter.formatSource("public class Test{public static void main(String[] args) {String s;}}"));
      } catch (FormatterException e) {
        e.printStackTrace();
    }
 }

}

and output will be

public class Test {
  public static void main(String[] args) {
     String s;
  }
}

Sample working code Sample

Hope this would helps to you

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

5 Comments

Don't post links only, an answer should include an explanation and the interesting content. See How to Answer
added the example please check it
Better but... Don't post your code in an image. Copy paste it using the { } button. It allow search engine to use the text to be referenced.
How can I implement this to android, using android studio?
Same way as how you are importing/linking jar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.