如何在Java中交换字符串字符

如何在Java中交换字符串字符

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

问题描述

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

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

推荐答案

由于String对象是不可变的,因此通过 toCharArray ,交换字符,然后通过char[]创建新的String href ="http://java.sun.com/javase/6/docs/api/java/lang/String.html#String(char [])" rel ="noreferrer"> 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中交换字符串字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:17