如何在Java中交换字符串字符? [英] How to swap String characters in Java?

查看:177
本文介绍了如何在Java中交换字符串字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在String中交换两个字符?例如,"abcde"将变为"bacde".

How can I swap two characters in a String? For example, "abcde" will become "bacde".

推荐答案

由于String对象是不可变的,因此通过 String(char[]) 构造函数会起作用.

Since String objects are immutable, going to a char[] via toCharArray, swapping the characters, then making a new String from char[] via the String(char[]) constructor would work.

以下示例交换了第一个和第二个字符:

The following example swaps the first and second characters:

String originalString = "abcde";

char[] c = originalString.toCharArray();

// Replace with a "swap" function, if desired:
char temp = c[0];
c[0] = c[1];
c[1] = temp;

String swappedString = new String(c);

System.out.println(originalString);
System.out.println(swappedString);

结果:

abcde
bacde

这篇关于如何在Java中交换字符串字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆