如何使用将字符串拆分为没有特殊字符的字符数组?

时间:2013-09-06 14:55:42

标签: java

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

}   

但是,我不知道如何相信数组以消除任何差距,我不知道如何删除重复的字符,我想我正在努力使它变得比它需要的更多

5 个答案:

答案 0 :(得分:4)

您可以使用:

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

答案 1 :(得分:1)

这对regular expressions来说非常有用:

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

此处,[+=]字符类,由+=组成。您可以根据需要添加其他字符。

答案 2 :(得分: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]

答案 3 :(得分: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
    }
}

答案 4 :(得分: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;
}