在Java中交换字符串的字符
为了在Java中交换字符串的字符,我们可以使用可变的字符串生成器,因此在交换过程中我们不必关心新对象的创建。
在这种情况下,我们将创建一个根据交换字符的位置交换字符串字符的方法,该方法将交换字符的位置作为其参数。首先存储两个需要交换的字符,然后使用字符串生成器的setcharacter方法交换目标对象字符。
示例
public class SwapCharacters {
public static void main(String[] args) {
String str = "abcde";
System.out.println(swap(str,0,1));
System.out.println(swap(str,0,str.length()-1));
}
static String swap(String str , int i , int j ) {
StringBuilder strB = new StringBuilder(str);
char l = strB.charAt(i) , r = strB.charAt(j);
strB.setCharAt(i,r);
strB.setCharAt(j,l);
return strB.toString();
}
}输出结果
bacde ebcda
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短