Java String Indent Format indent2(String text, String indent)

Here you can find the source of indent2(String text, String indent)

Description

Indents all but the first line using the given indent string.

License

Apache License

Parameter

Parameter Description
text The text to indent, may be null.
indent The string to put before the start of each but the first line.

Return

The indented text.

Declaration

public static String indent2(String text, String indent) 

Method Source Code

//package com.java2s;
/**/*  w  w w  .j a  va2s  .c  o  m*/
 * Copyright 2011 The Open Source Research Group,
 *                University of Erlangen-N?rnberg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Indents all but the first line using the given indent string.
     * 
     * @param text
     *            The text to indent, may be null.
     * @param indent
     *            The string to put before the start of each but the first line.
     * @return The indented text.
     */
    public static String indent2(String text, String indent) {
        if (text == null)
            return "";

        int n = text.length();
        StringBuilder result = new StringBuilder(n * 2);
        for (int i = 0; i < n; ++i) {
            char ch = text.charAt(i);
            result.append(ch);
            switch (ch) {
            case '\n':
                result.append(indent);
                break;

            case '\r':
                if (i + 1 < n && text.charAt(i + 1) == '\n') {
                    result.append('\n');
                    ++i;
                }
                result.append(indent);
                break;
            }
        }

        return result.toString();
    }
}

Related

  1. indent(StringBuilder builder, int indent)
  2. indent(StringBuilder builder, int indent)
  3. indent(StringBuilder builder, int times)
  4. indent(StringBuilder sb, int indent)
  5. indent(StringBuilder sb, int indent)
  6. indentAllLines(String s, String indent)
  7. indentation(int howMany)
  8. indentation(int numberOfIndent)
  9. indentationLevel(CharSequence c)