Reputation: 71
So I'm trying to sort a string array(global variable), although I'm able to ignore the case sensitivity, I need help in ignoring the symbols that come before the first alphabet, e.g. ~abc, etc..
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
}
}
}
}
Upvotes: 0
Views: 872
Reputation: 71
ok, so i came up with this code. It compiles but gets stuck in an endless loop while running; however, when i don't ignore the symbols, it does run (takes 18 seconds to sort and write, maybe because there r 30,000 words..) otherwise, it gets stuck in an endless loop
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);
}
}
}
Upvotes: -1
Reputation: 14611
You can remove control characters by replacing all characters which match:
\p{Cntrl}
- A control character: [\x00-\x1F\x7F]
Here is an example of how you can do this:
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);
}
This prints out:
With control characters: [B, AAA, AB]
No control characters: [AAA, AB, B]
Upvotes: 1
Reputation: 333
You can drop all the special characters and do a sort.
// 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);
Upvotes: 1