【java】字符串排序增加去重(附源码)
字符串排序增加去重
Java实现对字符串进⾏升序或是降序排列,在指定位置添加元素,对字符串去重。
使⽤函数:
String.charAt(int ):char 对字符串进⾏下标元素读取;
StringBuffer.append(String|char ): StringBuffer 将元素添加到StringBuffer中;
StringBuffer.charAt(int ): char 对StringBuffer内字符串进⾏下标元素读取;
完整源码如下:
1import java.util.*;
2
3public class pra1 {
4public static void main(String[] args) {
5 Scanner scan = new Scanner(System.in);
6 System.out.println("start");
7 String str = Line();
8 System.out.println("第⼆个参数⼤于0即为升序排列:" + string.sort(str, 1));
9char 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("去重:" + ve(str1));
13 }
14 }
java中字符串转数组15
16class string {
17public static String sort(String string, int a) {// 排序,可升降都可以
18char str[] = CharArray();
19int n = str.length;
20if (a > 0) {
21for (int i = 0; i < n; i++) {
22for (int j = 0; j < n - 1 - i; j++) {
23if (compare(str[j], str[j + 1]) > 0) {
24char temp = str[j];
25 str[j] = str[j + 1];
26 str[j + 1] = temp;
27 }
28 }
29 }
30 } else {
31for (int i = 0; i < n; i++) {
32for (int j = 0; j < n - 1 - i; j++) {
33if (compare(str[j], str[j + 1]) < 0) {
34char temp = str[j];
35 str[j] = str[j + 1];
36 str[j + 1] = temp;
37 }
38 }
39 }
40 }
41return new String(str);
42 }
43
44public static int compare(char a, char b) {
45if (a > b)
46return 1;
47else if (a < b)
48return -1;
49else
50return 0;
51 }
52
53public static String insert(String str, int a, String insert) {// 在指定位置插⼊字符串
54 StringBuffer stringB = new StringBuffer();
55int n = str.length();
56
57if (n < a)
58return str + insert;
59for (int i = 0; i < a; i++) {
60 stringB.append(str.charAt(i));
61 }
62 stringB.append(insert);
63for (int j = a; j < n; j++) {
64 stringB.append(str.charAt(j));
65 }
String();
67 }
68
69public static String remove(String str) {// 去重70 StringBuffer stringB = new StringBuffer(); 71int n = str.length();
72if (n <= 1)
73return str;
74 stringB.append(str.charAt(0));
75
76for (int i = 1; i < n; i++) {
77int tag = 1;
78for (int j = 0; j < stringB.length(); j++) { 79if (stringB.charAt(j) == str.charAt(i)) { 80 tag = -1;
81break;
82 }
83 }
84if (tag == 1)
85 stringB.append(str.charAt(i));
86 }
String();
88 }
89 }
补⼀个⽐较⾼效的去重⽅法:
public static String remove(String str) {
char[] c = CharArray();
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;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论