Java中如何将字符串后半部分的h与t互相替换?
解决方案
要实现字符串后半部分的'h'和't'互换,你需要针对每个字符做判断替换,而非单纯交换字符位置。以下是几种可行的实现方式:
方法一:遍历字符数组逐个替换
这是最直观的实现方式,将后半部分转为字符数组后,遍历每个元素完成替换:
public class Tollring3 { public static void main(String args[]) { String base = "httthhhtth"; int half = base.length() / 2; String first = base.substring(0, half); String second = base.substring(half); System.out.println("Actual String :- " + base); System.out.println("First half: " + first); System.out.println("Original second half: " + second); // 将后半部分转为字符数组 char[] c = second.toCharArray(); // 遍历每个字符,替换h和t for (int i = 0; i < c.length; i++) { if (c[i] == 'h') { c[i] = 't'; } else if (c[i] == 't') { c[i] = 'h'; } // 其他字符保持不变(如果存在) } String swappedString = new String(c); System.out.println("Swapped second half: " + swappedString); // 拼接前后两部分得到最终字符串 String result = first + swappedString; System.out.println("Final result: " + result); } }
方法二:字符串替换技巧(仅适用于h和t互换场景)
利用字符串的replace方法,注意替换顺序避免覆盖冲突:先把'h'替换为临时字符,再替换't'为'h',最后把临时字符转为't':
public class Tollring3 { public static void main(String args[]) { String base = "httthhhtth"; int half = base.length() / 2; String first = base.substring(0, half); String second = base.substring(half); System.out.println("Actual String :- " + base); System.out.println("First half: " + first); System.out.println("Original second half: " + second); // 按顺序替换h和t,避免互相覆盖 String swappedString = second.replace('h', '#') .replace('t', 'h') .replace('#', 't'); System.out.println("Swapped second half: " + swappedString); String result = first + swappedString; System.out.println("Final result: " + result); } }
方法三:Java 8+ Stream API(简洁写法)
通过流处理每个字符,完成替换后拼接成字符串:
import java.util.stream.Collectors; public class Tollring3 { public static void main(String args[]) { String base = "httthhhtth"; int half = base.length() / 2; String first = base.substring(0, half); String second = base.substring(half); System.out.println("Actual String :- " + base); System.out.println("First half: " + first); System.out.println("Original second half: " + second); String swappedString = second.chars() .mapToObj(c -> (char) c) .map(ch -> ch == 'h' ? 't' : (ch == 't' ? 'h' : ch)) .map(String::valueOf) .collect(Collectors.joining()); System.out.println("Swapped second half: " + swappedString); String result = first + swappedString; System.out.println("Final result: " + result); } }
输出结果
以上三种方法运行后都会得到:
Actual String :- httthhhtth First half: httth Original second half: hhtth Swapped second half: ttthh Final result: httthttthh
内容的提问来源于stack exchange,提问作者Ravi Ranjan
相关产品推荐
相关产品推荐

