如何在方法中更改字符串的字符? (相同的字符,随机顺序)

时间:2016-03-02 10:07:30

标签: java eclipse string methods char

//请帮我修复此代码。我想返回一个字符串,它与发送字符串具有相同的字符,但顺序不同。

public static String mix(String s){
        int random;
        int n= s.length();
        int [] control = new int[n];
        String miX="";

    for(int i=0 ; i < n ; i++){
        random = (int)(1+Math.random()*(n));
            if( control[i] != random  ){
                control[i]= random;
                miX += s.charAt(random);
        }
        }
        return miX;
    }

3 个答案:

答案 0 :(得分:1)

您可以使用Collections.shuffle。

String word= "word";
ArrayList<Character> chars =newArrayList<Character>(word.length());

for(char c : word.toCharArray()){
chars.add(c); }

Collections.shuffle(chars);
char[] shuffled =newchar[chars.size()];

for(int i =0; i < shuffled.length; i++){
 shuffled[i]= chars.get(i);
}

String shuffledWord =newString(shuffled);

与不使用函数的代码类似的另一种方法是:

public static void main(String[] args) {

// Create a random object
Random r = new Random();

String word = "Animals";

System.out.println("Before: " + word );
word = scramble( r, word );
System.out.println("After : " + word );
}
  public static String scramble( Random random, String inputString )
{
    // Convert your string into a simple char array:
    char a[] = inputString.toCharArray();

    // Scramble the letters

    for( int i=0 ; i<a.length-1 ; i++ )
   {
        int j = random.nextInt(a.length-1);
        // Swap letters
       char temp = a[i]; a[i] = a[j];  a[j] = temp;
  }       

    return new String( a );
 }

答案 1 :(得分:0)

您应该在String RANDOMLY的长度内选择两个位置,然后进行交换。 在循环中运行此任意次数,具体取决于您在String中所需的随机数量。

根据您的代码,如果随机选择两次相同的索引,您可能会错过新字符串中的某些字符

答案 2 :(得分:0)

Mix string chars with this code

import java.util.*;

class MixStringChars
{
    public static String mix(String s)
    {
        StringBuilder sb = new StringBuilder(s);
        Random r = new Random();
        for (int i = 0; i < s.length(); i++)
        {
            char curr = sb.charAt(i);          //current char
            int  rix  = r.nextInt(s.length()); //random index
            char temp = sb.charAt(rix);        //memorize char at index rix
            sb.setCharAt(rix, curr);           //put current char to rix index
            sb.setCharAt(i  , temp);           //put memorized char to i index
        }
        return sb.toString();
    }

    public static void main (String[] args)
    {
        System.out.println(mix("Hello"));
    }
}