get Char array Length by filtering special chars - Java java.lang

Java examples for java.lang:char Array

Description

get Char array Length by filtering special chars

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        char[] chars = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.', 'c',
                'o', 'm', 'a', '1', };
        int specialCharsLength = 42;
        System.out.println(getCharsLength(chars, specialCharsLength));
    }/*from   w ww . j  av  a 2s .c o  m*/

    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;
    }

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

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

Related Tutorials