在SORT METHOD中忽略符号

时间:2018-04-11 09:25:37

标签: java arrays sorting symbols

所以我正在尝试对字符串数组(全局变量)进行排序,虽然我能够忽略区分大小写,但我需要帮助忽略第一个字母之前的符号,例如: ~abc等。

public void sort()
{   
    int n = myArray.length;
    for (int i=0; i<n-1; i++){
        for(int j=0; j<n-i-1; j++){
            if((myArray[j+1]).compareToIgnoreCase(myArray[j])<0){
                String temp = myArray[j];
                myArray[j] = myArray[j+1];
                myArray[j+1] = temp;
                //toLower
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以删除所有特殊字符并进行排序。

// Drop all special characters
List<String> collect = Arrays.asList(myArray).stream().map(e -> e.replaceAll("[YourSpeciallCharacterss]", "")).collect(Collectors.toList());
//sort the list
collect.sort(String::compareTo);

答案 1 :(得分:1)

您可以通过替换匹配的所有字符来删除控制字符:

\p{Cntrl} - 控制角色:[\x00-\x1F\x7F]

以下是如何执行此操作的示例:

public static void main(String[] args) throws IOException {

    List<String> list = Arrays.asList("\u0001" + "B", "\u0002" + "AAA", "\u0003" + "AB");
    System.out.println("With control characters: " + list.stream().sorted().collect(Collectors.toList()));
    Pattern removeControl = Pattern.compile("\\p{Cntrl}");
    List<String> sorted = list.stream().map(s -> removeControl.matcher(s)
        .replaceAll("")).sorted().collect(Collectors.toList());
    System.out.println("No control characters: " + sorted);
}

打印出来:

With control characters: [B, AAA, AB]
No control characters: [AAA, AB, B]

答案 2 :(得分:-1)

好的,所以我想出了这段代码。它编译但在运行时卡在无限循环中;然而,当我不忽略这些符号时,它确实会运行(排序和写入需要18秒,也许是因为有30,000个单词......)否则,它会陷入无限循环中

class IO {

String[] myArray = new String[30000];

public void read()
{

    try {
        Scanner myLocal = new Scanner( new File("dictionary.txt"));  
        while (myLocal.hasNextLine()){

                for (int i=0; i<myArray.length; i++){
                String a = myLocal.nextLine();
                myArray[i] = a;

            }
        }

    }
    catch(IOException e){
        System.out.println(e);
    }
}

public void sort()
{   
    int n = myArray.length;
    String myIgnore = "[^a-zA-Z]+";  // alpha only
    String word1 = "";
    String word2 = "";

    for (int i=0; i<n; i++){
        for(int j=1; j<n-i; j++){ 
        word1 = myArray[j-1].replaceAll(myIgnore,"");
        word2 = myArray[j].replaceAll(myIgnore,"");
        if (word1.compareTo(word2)>0){





    String temp = word1;
    word1=word2;
    word2=temp;



            }

        }


    } 



}

public void write()
{
    try{
        PrintStream writer = new PrintStream(new File("myIgnoreNew.txt"));
        for (int i=0; i<myArray.length; i++){
            writer.println(myArray[i] + "\n");
            }
            writer.close();
    }
    catch(IOException e){
        System.out.println(e);
    }


}

}