简体   繁体   中英

JAVA change value of string and copy it to another string

I have a method that randomly changes one character in a string then copy the string values with the changes to a new string variable then I want to assign that new variable back to the old variable so the old variable then prints out the new string values. Below is the code:

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

I want the output to be for example if I have 11111 as the input, then the method should randomly change one of the characters and set it to 0 and print out the output as 11011 . it doesn't matter which character get change.

You're making this too complicated; you can do it a lot more compactly:

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

You can use StringBuffer or StringBuilder to change a char with position here is an example :

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

So if the p = 2 you will get a result like this :

11111

2

11011

11111

您所需要的只是替换索引 'p 处的字符。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM