我写了一个排序函数,它可以对所有内容进行排序,但是如果两个单词之间有空格,它会将空格排序到开头并删除最后一个字符串元素,为什么会这样?我尝试了 String.trim() 方法来消除空格,但它没有用,我需要帮助
private void SortStringsActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String str = TextArea.getText();
String[] words = str.split(" ");
int length = words.length;
String temp;
for(int i=0; i<=length-1; i++){
for(int j=0; j <length-1;j++){
if(words[i].compareToIgnoreCase(words[j]) == 0 ){}
else if (words[i].compareToIgnoreCase(words[j]) < 0){
temp = words[i].trim();
words[i] = words[j].trim();
words[j] = temp;
}else{}
}
}
/*
String str2="";
for (int i=0; i < length-1; i++) {
str2+=words[i]+" ";
}
*/
StringBuilder str2 = new StringBuilder();
for(int i=0; i<length-1; i++) {
str2.append(words[i]).append(" ");
}
TextArea.setText(str2.toString());
}