You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java实现字符串首个单词转为驼峰格式的转换功能

Java 字符串格式转换实现方案

转换规则

从给出的示例可以提炼出统一转换规则:

  • 定位字符串中第一个出现的英文字母(a-z/A-Z)的位置
  • 该位置之前的所有字符(数字、符号、下划线、美元符等)完全保留原样
  • 第一个英文字母转为大写
  • 第一个英文字母之后、第一个非英文字母之前的连续英文字符全部转为小写
  • 第一个非英文字母之后的所有内容完全保留原样

实现代码

核心转换方法

public class StringFormatConverter {
    public static String convert(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        char[] chars = input.toCharArray();
        int len = chars.length;
        int firstAlphaIdx = -1;
        // 查找第一个英文字母的索引位置
        for (int i = 0; i < len; i++) {
            if (Character.isLetter(chars[i])) {
                firstAlphaIdx = i;
                break;
            }
        }
        // 无英文字母直接返回原字符串
        if (firstAlphaIdx == -1) {
            return input;
        }
        // 首字母转大写
        chars[firstAlphaIdx] = Character.toUpperCase(chars[firstAlphaIdx]);
        // 首字母后连续英文字符转小写,遇到非英文字符终止转换
        for (int i = firstAlphaIdx + 1; i < len; i++) {
            if (Character.isLetter(chars[i])) {
                chars[i] = Character.toLowerCase(chars[i]);
            } else {
                break;
            }
        }
        return new String(chars);
    }
}

测试验证代码

public class ConverterTest {
    public static void main(String[] args) {
        // 包含所有示例及边界场景的测试用例
        Object[][] testCases = {
                {"1234_hello", "1234_Hello"},
                {"hello Data", "Hello Data"},
                {"hELLO data", "Hello data"},
                {"1234hEllo", "1234Hello"},
                {"heLLO1234hEllo", "Hello1234hEllo"},
                {"$hello", "$Hello"},
                {"123456", "123456"},
                {"", ""}
        };
        for (Object[] testCase : testCases) {
            String input = (String) testCase[0];
            String expected = (String) testCase[1];
            String result = StringFormatConverter.convert(input);
            System.out.printf("输入:%s | 预期输出:%s | 实际输出:%s | 测试结果:%s%n",
                    input, expected, result, expected.equals(result) ? "通过" : "不通过");
        }
    }
}

运行测试类的main方法即可验证所有场景,给出的示例全部可以匹配预期输出。

内容的提问来源于stack exchange,提问作者Supriya Shelar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 11:03:04