33

如何交换a 中的两个字符String?例如,"abcde"将成为"bacde".

4

16 回答 16

57

由于String对象是不可变的,因此转到char[]via toCharArray,交换字符,然后通过构造函数创建一个 new Stringfrom将起作用。char[]String(char[])

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

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
于 2009-06-05T14:39:01.333 回答
30

'在'一个字符串中,你不能。字符串是不可变的。您可以使用以下命令轻松创建第二个字符串:

 String second = first.replaceFirst("(.)(.)", "$2$1");
于 2009-06-05T14:38:05.873 回答
10

这已经回答了几次,但这里还有一个只是为了好玩:-)

public class Tmp {
    public static void main(String[] args) {
        System.out.println(swapChars("abcde", 0, 1));
    }
    private static String swapChars(String str, int lIdx, int rIdx) {
        StringBuilder sb = new StringBuilder(str);
        char l = sb.charAt(lIdx), r = sb.charAt(rIdx);
        sb.setCharAt(lIdx, r);
        sb.setCharAt(rIdx, l);
        return sb.toString();
    }
}
于 2009-06-05T20:02:44.383 回答
7
StringBuilder sb = new StringBuilder("abcde");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
String newString = sb.toString();
于 2014-03-30T14:02:54.017 回答
7
static String  string_swap(String str, int x, int y)
{

    if( x < 0 || x >= str.length() || y < 0 || y >= str.length())
    return "Invalid index";

    char arr[] = str.toCharArray();
    char tmp = arr[x];
    arr[x] = arr[y];
    arr[y] = tmp;

    return new String(arr);
}
于 2015-10-10T03:10:46.007 回答
2

String.toCharArray()会给你一个代表这个字符串的字符数组。

您可以在不更改原始字符串的情况下更改它(交换您需要的任何字符),然后使用String(char[])创建一个新字符串。

请注意,字符串是不可变的,因此您必须创建一个新的字符串对象。

于 2009-06-05T14:40:14.387 回答
1

这是用于递归交换 java 字符的 java 示例代码。您可以在http://java2novice.com/java-interview-programs/string-reverse-recursive/获得完整的示例代码

public String reverseString(String str){

    if(str.length() == 1){
        return str;
    } else {
        reverse += str.charAt(str.length()-1)
                +reverseString(str.substring(0,str.length()-1));
        return reverse;
    }
}
于 2012-07-24T17:15:18.137 回答
0

String.replaceAll() 或 replaceFirst()

String s = "abcde".replaceAll("ab", "ba")

链接到 JavaDocs字符串 API

于 2009-06-05T14:37:06.733 回答
0
public static String shuffle(String s) {
    List<String> letters = Arrays.asList(s.split(""));
    Collections.shuffle(letters);
    StringBuilder t = new StringBuilder(s.length());
    for (String k : letters) {
        t.append(k);
    }
    return t.toString();
}
于 2016-04-04T21:45:47.047 回答
0
//this is a very basic way of how to order a string alpha-wise, this does not use anything fancy and is great for school use

package string_sorter;

public class String_Sorter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String word = "jihgfedcba";
        for (int endOfString = word.length(); endOfString > 0; endOfString--) {

            int largestWord = word.charAt(0);
            int location = 0;
            for (int index = 0; index < endOfString; index++) {

                if (word.charAt(index) > largestWord) {

                    largestWord = word.charAt(index);
                    location = index;
                }
            }

            if (location < endOfString - 1) {

                String newString = word.substring(0, location) + word.charAt(endOfString - 1) + word.substring(location + 1, endOfString - 1) + word.charAt(location);
                word = newString;
            }
            System.out.println(word);
        }

        System.out.println(word);
    }

}
于 2018-12-28T01:21:59.723 回答
0
private static void interchangeSpecificCharInString(String originalStr, String inter1, String inter2) {
        List<Character> characterList = new ArrayList<>();

        for (char c : originalStr.toCharArray()) {
            characterList.add(c);
        }

        int index1 = characterList.indexOf(inter1.charAt(0));
        int index2 = characterList.indexOf(inter2.charAt(0));

        characterList.set(index1, inter2.charAt(0));
        characterList.set(index2, inter1.charAt(0));

        StringBuilder sb = new StringBuilder();
        for (char c : characterList) {
            sb.append(c);
        }

        System.out.println(sb.toString());
    }

如果您要传递的字符串是“Random”,那么您想交换“R”和“m”,那么这里 originalStr 将是 Random,inter1 将是 R,inter2 将是 m。

于 2021-09-23T09:26:24.590 回答
0
s = s.substring(0, firstChar)
            +s.charAt(secondChar)
            +s.substring(firstChar + 1, secondChar)
            +s.charAt(firstChar)
            +s.substring(secondChar+1);
于 2020-12-11T12:25:52.497 回答
0

我认为这应该有所帮助。

import java.util.*;

public class StringSwap{

public static void main(String ar[]){
    Scanner in = new Scanner(System.in);
    String s = in.next();
    System.out.println(new StringBuffer(s.substring(0,2)).reverse().toString().concat(s.substring(2)));
  }
}
于 2016-07-25T07:26:07.380 回答
0

这是一个解决方案StringBuilder。它支持使用填充字符填充字符串长度不均匀的结果字符串。正如您已经猜到的那样,此方法用于十六进制半字节交换。

/**
 * Swaps every character at position i with the character at position i + 1 in the given
 * string.
 */
public static String swapCharacters(final String value, final boolean padding)
{
   if ( value == null )
   {
      return null;
   }

   final StringBuilder stringBuilder = new StringBuilder();
   int posA = 0;
   int posB = 1;
   final char padChar = 'F';

   // swap characters
   while ( posA < value.length() && posB < value.length() )
   {
      stringBuilder.append( value.charAt( posB ) ).append( value.charAt( posA ) );
      posA += 2;
      posB += 2;
   }

   // if resulting string is still smaller than original string we missed the last
   // character
   if ( stringBuilder.length() < value.length() )
   {
      stringBuilder.append( value.charAt( posA ) );
   }

   // add the padding character for uneven strings
   if ( padding && value.length() % 2 != 0 )
   {
      stringBuilder.append( padChar );
   }

   return stringBuilder.toString();
}
于 2015-10-15T11:32:20.127 回答
-1
import java.io.*;
class swaping
{
     public static void main(String args[]) 
     {
         String name="premkumarg";
         int len=name.length();
         char[] c = name.toCharArray();
         for(int i=0;i<len-1;i=i+2)
         {
             char temp= c[i];
             c[i]=c[i+1];
             c[i+1]=temp;
         }

         System.out.println("Swapping string is: ");
         System.out.println(c);

    }
}
于 2013-09-12T09:17:34.043 回答
-1

以下代码行将交换 中的前两个字符str

return str.charAt(1) + str.charAt(0) + str.substring(2);
于 2016-08-21T13:42:53.723 回答