java替换重复的字符 [英] java replace duplicate characters

查看:445
本文介绍了java替换重复的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以对于作业,我必须生成一个随机代码,并有人猜到控制台中的代码。现在我的问题是,我似乎找不到一种方法来替换代码中的任何重复的字符。代码必须在ABCDEF范围内,并且包含4个字母。这是我到目前为止:

So for an assignment I have to generate a random code, and have someone guess the code in the console. Now My problem is that I can't seem to find a way to replace any duplicate characters in the code. The code must range in "ABCDEF", and contain 4 letters. This is what I got so far:

    char codeLetters;
    String masterCode;
    StringBuilder strings = new StringBuilder(); 
    Random random = new Random();

    for (int i = 0; i < 4; i++) {
        codeLetters = code[random.nextInt(code.length)];
        strings.append(codeLetters);
    }
    masterCode = strings.toString();
    String temp = "";
    boolean isDuplicate = false;

    for (int i = 0; i < masterCode.length(); i++) {
        isDuplicate = false;
        char comparisonChar = masterCode.charAt(i);
        for (int j = i + 1; j < masterCode.length(); j++) {
            char nextChar = masterCode.charAt(j);
            if (comparisonChar == nextChar) isDuplicate = true;
        }
        if (!isDuplicate) temp = temp + comparisonChar;
    }
    masterCode = temp;

    System.out.println(masterCode);

它打印由2-3个字母组成的代码,或包含5或6个字母的代码,很少有一个正确的代码与4个字母。这个代码根据我所知道的不是添加重复的字符,但是我希望它替换为另一个字符。有没有什么可以用另一个随机生成的字符替换字符,这个字符串不在String中,而不使用Sets?

it prints either a code consisting out of 2-3 letters, or a code containing 5 or 6 letters, and rarely a correct code with 4 letters. What this code does as far as I know is not add the duplicate characters, but I want it to Replace them instead with another character. Is there someway to replace the characters with another randomly generated char, which is not in the String yet, without using Sets?

推荐答案

听起来你只想使用代码中的每个字母?为什么不从一开始就使用 ArrayList 设置它,如果随机选择,则删除每个字符:

It sounds like you only want to use each letter in code once? Why don't you set that up from the beginning using an ArrayList, and removing each character if it is randomly selected:

// copy `code` into a temporary arraylist
ArrayList<Character> possibleLetters = new ArrayList<Character>(code.length);
for (char c : code) possibleLetters.add(c);
// select randomly "without replacement"
for (int i = 0; i < 4; i++) {
    int index = random.nextInt(possibleLetters.size());
    codeLetters = possibleLetters.remove(index);
    strings.append(codeLetters);
}

这篇关于java替换重复的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆