如何用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
相关产品推荐
相关产品推荐

