Java ASCII asciiFill2(String str, int startIdx, String fillStr)

Here you can find the source of asciiFill2(String str, int startIdx, String fillStr)

Description

ascii Fill

License

Apache License

Declaration

public static String asciiFill2(String str, int startIdx, String fillStr) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {

    public static String asciiFill2(String str, int startIdx, String fillStr) {
        int idx = asciiIdx2StrIdx(str, startIdx);
        String ret = "";
        if (idx == -1) {
            ret = asciiPaddingR(str, startIdx, " ");
            ret += fillStr;/*from   w w  w.  j  a  v a2 s.c o  m*/
        } else {
            ret = str.substring(0, idx) + fillStr;
            if (ret.length() < str.length())
                ret += str.substring(ret.length());
        }
        return ret;
    }

    public static int asciiIdx2StrIdx(String str, int asciiIdx) {
        int length = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            length += c > 127 ? 2 : 1;
            if (length >= asciiIdx)
                return i;
        }

        return -1;
    }

    public static String asciiPaddingR(String str, int length,
            String padding) {
        String rst = asciiTrimR(str, length);
        int alen = asciiLength(rst);
        if (alen == length)
            return rst;
        rst += repeat(padding, (length - alen) / asciiLength(padding));
        return rst;
    }

    public static String asciiTrimR(String str, int length) {
        int alen = asciiLength(str);
        if (alen <= length)
            return str;
        String result = "";
        alen = 0;
        for (int i = 0; i < length; i++) {
            char c = str.charAt(i);
            alen += c > 127 ? 2 : 1;
            if (alen <= length)
                result += c;
            else
                break;
        }
        return result;
    }

    public static int asciiLength(String str) {
        int length = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            length += c > 127 ? 2 : 1;
        }

        return length;
    }

    public static String repeat(String str, int times) {
        String r = "";
        for (int i = 0; i < times; i++)
            r += str;
        return r;
    }
}

Related

  1. asciiDump(byte[] in)
  2. asciiEbcdic(String source)
  3. asciiEndsWithIgnoreCase(String source, String suffix)
  4. asciiEqualsIgnoreCase(byte[] a, byte[] b)
  5. asciiEqualsIgnoreCase(byte[] buf1, byte[] buf2)
  6. asciify(String s)
  7. asciiIdx2StrIdx(String str, int asciiIdx)
  8. asciiLength(String str)
  9. asciiPaddingR(String str, int length, String padding)