在Mybatis中可以通过配置实现驼峰式命名自动转换,简单的实现以下这个小功能。这个也没啥算法可言,就是一个简单的字符串处理,模拟一下就好了。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| public class autoCamelcase { public static String[] input; public static String[] output; public static void main(String[] args) { initInput(); solve(); print(); } public static void initInput() { input = new String[] { "aaaa_bbbb_ccccc", "first_name", "email", "q_q_q_q_q_q_q" }; } public static void solve() { int n = input.length; output = new String[n]; for (int i = 0; i < n; i++) { int len = input[i].length(); int firstIdx = 0; while (firstIdx < len && input[i].charAt(firstIdx) != '_') { firstIdx++; } if (firstIdx == len) { output[i] = input[i]; } else { output[i] = ""; output[i] += input[i].substring(0, firstIdx); for (int l = firstIdx, r = firstIdx; l < len; r++, l = r) { while (r + 1 < len && input[i].charAt(r + 1) != '_') r++; output[i] += (char)(input[i].charAt(l + 1) - 32); if (l + 2 <= r) { output[i] += input[i].substring(l + 2, r + 1); } } } } } public static void print() { for (String v : output) { System.out.println(v); } } }
|
结果