How to swap String characters in Java?

后端 未结 14 2210
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 14:22

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

相关标签:
14条回答
  • 2020-12-08 14:55

    String.replaceAll() or replaceFirst()

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

    Link to the JavaDocs String API

    0 讨论(0)
  • 2020-12-08 14:55
    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);
    
        }
    }
    
    0 讨论(0)
  • 2020-12-08 14:58

    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)));
      }
    }
    
    0 讨论(0)
  • 2020-12-08 14:59

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-08 14:59

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-08 15:00
    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();
    }
    
    0 讨论(0)
提交回复
热议问题