字符串排序增加去重
Java实现对字符串进行升序或是降序排列,在指定位置添加元素,对字符串去重。
使用函数:
String.toCharArray():char[] 将字符串转化为字符数组;
String.charAt(int ):char 对字符串进行下标元素读取;
StringBuffer.append(String|char ): StringBuffer 将元素添加到StringBuffer中;
StringBuffer.charAt(int ): char 对StringBuffer内字符串进行下标元素读取;
StringBuffer.toString():String 将StringBuffer.转换为String类型。
完整源码如下:
1 import java.util.*; 2 3 public class pra1 { 4 public static void main(String[] args) { 5 Scanner scan = new Scanner(System.in); 6 System.out.println("start"); 7 String str = scan.nextLine(); 8 System.out.println("第二个参数大于0即为升序排列:" + string.sort(str, 1)); 9 char a[] = { 'c', 'b', 'd' }; 10 String str1 = string.insert(str, 3, new String(a)); 11 System.out.println("在位置3处插入a[]内元素:" + str1); 12 System.out.println("去重:" + string.remove(str1)); 13 } 14 } 15 16 class string { 17 public static String sort(String string, int a) {// 排序,可升降都可以 18 char str[] = string.toCharArray(); 19 int n = str.length; 20 if (a > 0) { 21 for (int i = 0; i < n; i++) { 22 for (int j = 0; j < n - 1 - i; j++) { 23 if (compare(str[j], str[j + 1]) > 0) { 24 char temp = str[j]; 25 str[j] = str[j + 1]; 26 str[j + 1] = temp; 27 } 28 } 29 } 30 } else { 31 for (int i = 0; i < n; i++) { 32 for (int j = 0; j < n - 1 - i; j++) { 33 if (compare(str[j], str[j + 1]) < 0) { 34 char temp = str[j]; 35 str[j] = str[j + 1]; 36 str[j + 1] = temp; 37 } 38 } 39 } 40 } 41 return new String(str); 42 } 43 44 public static int compare(char a, char b) { 45 if (a > b) 46 return 1; 47 else if (a < b) 48 return -1; 49 else 50 return 0; 51 } 52 53 public static String insert(String str, int a, String insert) {// 在指定位置插入字符串 54 StringBuffer stringB = new StringBuffer(); 55 int n = str.length(); 56 57 if (n < a) 58 return str + insert; 59 for (int i = 0; i < a; i++) { 60 stringB.append(str.charAt(i)); 61 } 62 stringB.append(insert); 63 for (int j = a; j < n; j++) { 64 stringB.append(str.charAt(j)); 65 } 66 return stringB.toString(); 67 } 68 69 public static String remove(String str) {// 去重 70 StringBuffer stringB = new StringBuffer(); 71 int n = str.length(); 72 if (n <= 1) 73 return str; 74 stringB.append(str.charAt(0)); 75 76 for (int i = 1; i < n; i++) { 77 int tag = 1; 78 for (int j = 0; j < stringB.length(); j++) { 79 if (stringB.charAt(j) == str.charAt(i)) { 80 tag = -1; 81 break; 82 } 83 } 84 if (tag == 1) 85 stringB.append(str.charAt(i)); 86 } 87 return stringB.toString(); 88 } 89 }
补一个比较高效的去重方法:
public static String remove(String str) {
char[] c = str.toCharArray(); char[] s = new char[128]; for (int i = 0; i < c.length; i++) { s[c[i]] = c[i]; } String strQ = ""; for (int i = 0; i < s.length; i++) { if((int)s[i] != 0){ strQ += s[i]; } } return strQ; }