JAVA更改字符串的值并将其复制到另一个字符串

时间:2017-01-30 17:41:03

标签: java string

我有一个方法随机更改字符串中的一个字符,然后将字符串值与更改复制到新的字符串变量然后我想将该新变量分配回旧变量,以便旧变量然后打印出新变量字符串值。以下是代码:

public class Test {

    public static void main(String[] args) {
        SmallChange();
    }

    public static void SmallChange() {
        String s = "11111";
        System.out.println(s);
        int n = s.length();
        Random rand = new Random();

        int p = rand.nextInt(n);
        System.out.println(p);
        String x = "";
        char[] a = new char[n];

        if (s.charAt(p) == '0') {
            s = "" + 1;
        } else if (s.charAt(p) == '1') {
            s = "" + 0;
        }
        s.getChars(0, n, a, 0);
        x = a.toString();

        s = x;

        System.out.println(s);
    }
}

我希望输出是例如如果我有 11111 作为输入,那么该方法应该随机更改其中一个字符并将其设置为0并将输出打印为 11011 即可。

。哪个角色有所改变并不重要。

3 个答案:

答案 0 :(得分:1)

你让这太复杂了;你可以更紧凑地做到这一点:

int position = (int)(Math.random() * s.length() - 1); // Get a random position
x = s.substring(0, position) + s.charAt(position) == '0' ? '1' : '0' + s.substring(position + 1); // Create the string

答案 1 :(得分:1)

您可以使用StringBufferStringBuilder更改位置字符,这是一个示例:

public static void SmallChange() {
    String s = "11111";
    System.out.println(s);
    int n = s.length();
    Random rand = new Random();

    int p = rand.nextInt(n);
    System.out.println(p);
    StringBuffer sb = new StringBuffer(s);
    sb.setCharAt(p, '0');
    System.out.println(sb);
    System.out.println(s);
}

所以,如果p = 2你得到这样的结果:

  

11111

     

2

     

11011

     

11111

答案 2 :(得分:0)

您需要的只是替换索引' p。

中的字符

s = s.substring(0,p)+(1-Integer.parseInt(s.substring(p, p+1)))+s.substring(p+1);