Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    public static String getStringByLength(String string, int length) {
        StringBuffer stringBuffer = new StringBuffer();

        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";

        for (int i = 0; i < string.length(); i++) {

            String temp = string.substring(i, i + 1);
            if (temp.matches(chinese)) {
                if (valueLength >= (length - 1))
                    break;
                valueLength += 2;

            } else {
                if (valueLength >= length)
                    break;
                valueLength += 1;

            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}