[英]How to use split a string into character array without special characters?
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;
}
}
但是,我不知道如何壓縮數組以消除任何間隙,也不知道如何消除重復的字符,我想這使它比需要的難
您可以使用:
_string.replaceAll("[+,=]","");
這聽起來像是正則表達式的好用法:
String result = _string.replaceAll("[+=]", "");
在這里, [+=]
是由+
和=
組成的字符類 。 您可以根據需要添加其他字符。
嘗試下一個:
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]
或者,您可以設置另一個數組,如下所示:
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
}
}
retains order). 您可以擴展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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.