Android String Sub String Get substring(String str, int srcPos, int specialCharsLength)

Here you can find the source of substring(String str, int srcPos, int specialCharsLength)

Description

substring

License

Open Source License

Declaration

public static String substring(String str, int srcPos,
        int specialCharsLength) 

Method Source Code

//package com.java2s;

public class Main {

    public static String substring(String str, int srcPos,
            int specialCharsLength) {
        if (str == null || "".equals(str) || specialCharsLength < 1) {
            return "";
        }//from w  w  w .ja  va 2 s  . c  o m
        if (srcPos < 0) {
            srcPos = 0;
        }
        if (specialCharsLength <= 0) {
            return "";
        }
        char[] chars = str.toCharArray();
        if (srcPos > chars.length) {
            return "";
        }

        int strLength = 0;
        for (int i = 0; i < chars.length; i++) {
            strLength += getSpecialCharLength(chars[i]);
        }

        if (strLength < specialCharsLength) {
            return str;
        }
        int charsLength = getCharsLength(chars, specialCharsLength);
        return new StringBuffer()
                .append(new String(chars, srcPos, charsLength))
                .append("...").toString();
    }

    private static int getSpecialCharLength(char c) {
        if (isLetter(c)) {
            return 1;
        } else {
            return 2;
        }
    }

    private static int getCharsLength(char[] chars, int specialCharsLength) {
        int count = 0;
        int normalCharsLength = 0;
        for (int i = 0; i < chars.length; i++) {
            int specialCharLength = getSpecialCharLength(chars[i]);
            if (count <= specialCharsLength - specialCharLength) {
                count += specialCharLength;
                normalCharsLength++;
            } else {
                break;
            }
        }
        return normalCharsLength;
    }

    public static boolean isLetter(char c) {
        int k = 0x80;
        return c / k == 0 ? true : false;
    }
}

Related

  1. substring(String str, int toCount)
  2. substring(String str, int len, String more)
  3. substringFromLast(final String str, final String separator)
  4. substringToLast(final String str, final String separator)
  5. takeOutFirstChar(String input)
  6. substringAfter(String text, char c)
  7. substringAfterLast(String text, char separator)
  8. substringBefore(String text, char separator)
  9. substringBefore(String text, char separator)