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

发布于 2024-07-22 22:51:30 字数 100 浏览 9 评论 0原文

如何交换字符串中的两个字符? 例如,“abcde”将变为“bacde”

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

超可爱的懒熊 2024-07-29 22:51:30

由于 String 对象是不可变的,因此通过 toCharArray,交换字符,然后从 创建一个新的 String >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

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);

Result:

abcde
bacde
焚却相思 2024-07-29 22:51:30

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

 String second = first.replaceFirst("(.)(.)", "$2$1");

'In' a string, you cant. Strings are immutable. You can easily create a second string with:

 String second = first.replaceFirst("(.)(.)", "$2$1");
你是暖光i 2024-07-29 22:51:30

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

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();
    }
}

This has been answered a few times but here's one more just for fun :-)

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();
    }
}
面犯桃花 2024-07-29 22:51:30
StringBuilder sb = new StringBuilder("abcde");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
String newString = sb.toString();
StringBuilder sb = new StringBuilder("abcde");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
String newString = sb.toString();
心碎的声音 2024-07-29 22:51:30
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);
}
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);
}
谈场末日恋爱 2024-07-29 22:51:30

String.toCharArray()< /a> 将为您提供代表该字符串的字符数组。

您可以在不更改原始字符串的情况下更改此设置(交换所需的任何字符),然后使用 字符串(char[])

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

String.toCharArray() will give you an array of characters representing this string.

You can change this without changing the original string (swap any characters you require), and then create a new string using String(char[]).

Note that strings are immutable, so you have to create a new string object.

脸赞 2024-07-29 22:51:30

这是用于递归交换 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;
    }
}

Here is java sample code for swapping java chars recursively.. You can get full sample code at 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;
    }
}
扎心 2024-07-29 22:51:30

String.replaceAll() 或 ReplaceFirst()

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

链接到 JavaDocs 字符串 API

String.replaceAll() or replaceFirst()

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

Link to the JavaDocs String API

笑饮青盏花 2024-07-29 22:51:30

这是使用 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();
}

Here's a solution with a StringBuilder. It supports padding resulting strings with uneven string length with a padding character. As you've guessed this method is made for hexadecimal-nibble-swapping.

/**
 * 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();
}
孤独患者 2024-07-29 22:51:30
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();
}
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();
}
油饼 2024-07-29 22:51:30

我认为这应该有帮助。

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)));
  }
}

I think this should help.

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)));
  }
}
久夏青 2024-07-29 22:51:30
s = s.substring(0, firstChar)
            +s.charAt(secondChar)
            +s.substring(firstChar + 1, secondChar)
            +s.charAt(firstChar)
            +s.substring(secondChar+1);
s = s.substring(0, firstChar)
            +s.charAt(secondChar)
            +s.substring(firstChar + 1, secondChar)
            +s.charAt(firstChar)
            +s.substring(secondChar+1);
陪你搞怪i 2024-07-29 22:51:30
//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);
    }

}
//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);
    }

}
-小熊_ 2024-07-29 22:51:30
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。

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());
    }

If the string that you want to pass on is "Random" then you want to interchange "R" and "m" then here the originalStr will be Random, inter1 will be R and inter2 will be m.

空名 2024-07-29 22:51:30
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);

    }
}
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);

    }
}
断舍离 2024-07-29 22:51:30

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

return str.charAt(1) + str.charAt(0) + str.substring(2);

The following line of code will swap the first two characters in str:

return str.charAt(1) + str.charAt(0) + str.substring(2);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文