package cn.reghao.tnb.sb.db.autobatis;

import java.util.ArrayList;
import java.util.List;

/**
 * @author reghao
 * @date 2021-08-10 15:50:46
 */
public class StringUtil {
    /**
     * 将 aaaBbbCcc 格式转化为 aaa_bbb_ccc 格式
     *
     * @date 2020-04-02 下午8:39
     */
    public static String separateByUnderline(String str) {
        List<String> list = new ArrayList<>();

        char[] chars = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        sb.append(chars[0]);

        for (int i = 1; i < chars.length; i++) {
            if (chars[i] > 96 && chars[i] < 123) {
                // lower case
                sb.append(chars[i]);
            } else if (chars[i] > 64 && chars[i] < 91) {
                list.add(sb.toString());
                sb.delete(0, sb.length());
                sb.append(chars[i]);
            }
        }
        list.add(sb.toString());
        sb.delete(0, sb.length());

        if (list.size() == 1) {
            return list.get(0).toLowerCase();
        }

        for (String s : list) {
            sb.append(s.toLowerCase()).append("_");
        }
        sb.deleteCharAt(sb.lastIndexOf("_"));
        return sb.toString();
    }
}
