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

如何用for循环实现字符串字符间加下划线且末尾无下划线?

解决字符串字符间加下划线且首尾无下划线的问题

你可以通过两种调整方式来避免末尾出现下划线:

方法一:先添加第一个字符,后续字符前加下划线

跳过第一个字符的前置下划线,从第二个字符开始,每次先加下划线再追加当前字符,这样就不会在末尾多出下划线:

public String spacedWord() {
    if (currentString.isEmpty()) { // 处理空字符串的边界情况,避免索引越界
        return "";
    }
    StringBuilder spacedString = new StringBuilder();
    // 先添加第一个字符
    spacedString.append(currentString.charAt(0));
    // 从第二个字符开始遍历
    for (int i = 1; i < currentString.length(); i++) {
        spacedString.append("_").append(currentString.charAt(i));
    }
    return spacedString.toString();
}

注意:这里用StringBuilder代替直接字符串拼接,因为循环里用+拼接字符串会频繁创建新对象,效率更低,尤其是处理较长字符串时。

方法二:遍历到倒数第二个字符,最后单独添加末尾字符

循环只处理到倒数第二个字符,每个字符后加下划线,最后再把最后一个字符单独追加进去:

public String spacedWord() {
    if (currentString.isEmpty()) {
        return "";
    }
    StringBuilder spacedString = new StringBuilder();
    // 遍历到倒数第二个字符
    for (int i = 0; i < currentString.length() - 1; i++) {
        spacedString.append(currentString.charAt(i)).append("_");
    }
    // 添加最后一个字符,不加下划线
    spacedString.append(currentString.charAt(currentString.length() - 1));
    return spacedString.toString();
}

测试输入"hi there",两种方法都会返回h_i__t_h_e_r_e;输入"hey there"会返回h_e_y_ _t_h_e_r_e,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:38:10