2
    Scanner _in = new Scanner(System.in);
    System.out.println("Enter an Equation of variables");
    String _string = _in.nextLine();


    char[] cArray = _string.toCharArray();

我想删除符号“+,=”并且我想删除任何重复的变量。

到目前为止,我有:

for(int i = 0; i < cArray.length; i++){
   if(cArray[i].equals(+)|| cArray[i].equals(=)){
           cArray[i] = null;
        }

}   

但是,我不知道如何让数组消除任何间隙,也不知道如何删除重复的字符,我认为我让这变得比它需要的更难

4

5 回答 5

4

您可以使用:

_string.replaceAll("[+,=]","");
于 2013-09-06T14:57:33.297 回答
1

这听起来像是正则表达式的一个很好的用途:

String result = _string.replaceAll("[+=]", "");

这里,[+=]是一个由和组成的字符类。您可以根据需要添加其他字符。+=

于 2013-09-06T14:58:25.893 回答
1

尝试下一个:

public static void main(String[] args) {
    String input = "a+a+b=c+d-a";

    char[] cArray = input.replaceAll("[-+=]", "")        // gaps
                         .replaceAll("(.)(?=.*\\1)", "") // repeating
                         .toCharArray();

    System.out.println(Arrays.toString(cArray));
}

输出:

[b, c, d, a]
于 2013-09-06T15:25:14.777 回答
0

或者您可以查看另一个数组,如下所示:

Scanner in = new Scanner(System.in);

String s = in.nextLine();
char [] cArray = s.toCharArray();

int count = 0;
char [] cArray2 = new char[cArray.length];

for (int i = 0; i < cArray.length; i++){
    if (cArray[i] != '+' || cArray[i] != '='){
        cArray2[count++] = cArray[i];
    }
}


for (int i = 0; i < count; i++){
    boolean repeated = false;

    for (int j = i + 1; j < count; j++){
        if (cArray2[i] == cArray2[j]){
            repeated = true;
            break;
        }
    }

    if (!repeated){
        //do what you want
    }
}
于 2013-09-06T15:09:21.667 回答
0

您可以扩展 LinkedHashSet (它强制唯一性保留顺序)。覆盖 add() 函数以不接受任何您不想使用的字符。然后将内容放入 char 数组中。

public static char[] toCharArray(String str) {

    // Here I am anonymously extending LinkedHashSet
    Set<Character> characters = new LinkedHashSet<Character>() {

        // Overriding the add method
        public boolean add(Character character) {
            if (!character.toString().matches("[\\+=]")) {
                // character is not '+' or '='
                return super.add(character);
            }
            // character is '+' or '='
            return false;
        }
    };

    // Adding characters from str to the set.
    // Duplicates, '+'s, and '='s will not be added.
    for (int i = 0; i < str.length(); i++) {
        characters.add(str.charAt(i));
    }

// Put Characters from set into a char[] and return.
    char[] arrayToReturn = new char[characters.size()];
    int i = 0;
    for (Character c : characters) {
        arrayToReturn[i++] = c;
    }
    return arrayToReturn;
}
于 2013-09-06T17:08:50.887 回答