㈠ java中怎麼對一串字元進行排序!
importjava.util.Arrays;
publicclassStringSort{
publicstaticvoidmain(String[]args){
Stringstring="togoodtoonostringandnow";
StringsortString=sortChar(string);
System.out.println(sortString);
}
privatestaticStringsortChar(Stringstr){
//1.將字元串轉化成數組
char[]chs=stringToArray(str);
//2.對數組進行排序
sort(chs);
//3.將數組轉成字元串
returntoString(chs);
}
privatestaticStringtoString(char[]chs){
returnnewString(chs);
}
//對字元數組進行升序排序
privatestaticvoidsort(char[]chs){
Arrays.sort(chs);
}
//將字元串轉化成為數組
privatestaticchar[]stringToArray(Stringstring){
returnstring.toCharArray();
}
}
㈡ java 字元串排序
//這個絕對滿足您的要求
import java.util.Arrays;
public class StringSort {
public static void main(String[] args) {
String ss[]={"ab","wang","hi","a","abff"};
MyString mySs[]=new MyString[ss.length];//創建自定義排序的數組
for (int i = 0; i < ss.length; i++) {
mySs[i]=new MyString(ss[i]);
}
Arrays.sort(mySs);//排序
for (int i = 0; i < mySs.length; i++) {
System.out.println(mySs[i].s);
}
}
}
class MyString implements Comparable<MyString>{
public String s;//包裝String
public MyString(String s) {
this.s = s;
}
@Override
public int compareTo(MyString o) {
if(o==null||o.s==null) return 1;
if(s.length()>o.s.length()) return 1;
else if(s.length()<o.s.length()) return -1;
return s.compareTo(o.s);
}
}
㈢ 編寫一個java程序對一個字元串數組進行排序
importjava.util.Arrays;
publicclassStringDateSort{
publicstaticvoidmain(String[]args){
StringnumString="2310-8037108";
StringsortStr=sortNumberString(numString);
System.out.println("排序的結果是"+sortStr);
}
(StringnumString){
//1.將給定的字元串分解成多個數字格式字元串
String[]numStrings=toStringArray(numString);
//2.將字元串數組轉成int數組
int[]nums=toIntArray(numStrings);
//3.對數組排序
sort(nums);
//4.將int數組轉成字元串
returntoString(nums);
}
privatestaticStringtoString(int[]nums){
StringBufferstringBuffer=newStringBuffer();
for(inti=0;i<nums.length;i++){
if(i!=nums.length-1){
stringBuffer.append(nums[i]+"<");
}else{
stringBuffer.append(nums[i]);
}
}
returnstringBuffer.toString();
}
privatestaticvoidsort(int[]nums){
Arrays.sort(nums);
}
privatestaticint[]toIntArray(String[]numStrings){
int[]nums=newint[numStrings.length];
for(inti=0;i<numStrings.length;i++){
Strings=numStrings[i];
nums[i]=Integer.parseInt(s);
}
returnnums;
}
privatestaticString[]toStringArray(StringnumString){
String[]numberStr=numString.split("");
for(inti=0;i<numberStr.length;i++){
System.out.println("抽出數字"+numberStr[i]);
}
returnnumberStr;
}
}