1583
|
1 package goodjava.util;
|
|
2
|
|
3 import java.io.UnsupportedEncodingException;
|
|
4 import java.util.Base64;
|
1720
|
5 import java.util.ArrayList;
|
1583
|
6
|
|
7
|
|
8 public final class GoodUtils {
|
|
9
|
|
10 public static byte[] getBytes(String s,String charsetName) {
|
|
11 try {
|
|
12 return s.getBytes(charsetName);
|
|
13 } catch(UnsupportedEncodingException e) {
|
|
14 throw new RuntimeException(e);
|
|
15 }
|
|
16 }
|
|
17
|
|
18 public static String base64Encode(String s) {
|
|
19 return Base64.getEncoder().encodeToString(getBytes(s,"UTF-8"));
|
|
20 }
|
1720
|
21
|
|
22 public static String[] split(String s,String splitter) {
|
|
23 return split(s,splitter,-1);
|
|
24 }
|
|
25
|
|
26 // modified from String.java
|
|
27 public static String[] split(String s,String splitter,int limit) {
|
|
28 int len = s.length();
|
|
29 int n = splitter.length();
|
|
30 int off = 0;
|
|
31 int next = 0;
|
|
32 boolean limited = limit > 0;
|
|
33 ArrayList<String> list = new ArrayList<>();
|
|
34 if( n==0 ) {
|
|
35 limit = limited ? Math.min(limit,len) : len;
|
|
36 for( int i=0; i<limit; i++ ) {
|
|
37 list.add(s.substring(i, i+1));
|
|
38 }
|
|
39 String[] result = new String[limit];
|
|
40 return list.toArray(result);
|
|
41 }
|
|
42 while ((next = s.indexOf(splitter, off)) != -1) {
|
|
43 if (!limited || list.size() < limit - 1) {
|
|
44 list.add(s.substring(off, next));
|
|
45 off = next + n;
|
|
46 } else { // last one
|
|
47 //assert (list.size() == limit - 1);
|
|
48 list.add(s.substring(off, len));
|
|
49 off = len;
|
|
50 break;
|
|
51 }
|
|
52 }
|
|
53 // If no match was found, return s
|
|
54 if (off == 0)
|
|
55 return new String[]{s};
|
|
56
|
|
57 // Add remaining segment
|
|
58 if (!limited || list.size() < limit)
|
|
59 list.add(s.substring(off, len));
|
|
60
|
|
61 // Construct result
|
|
62 int resultSize = list.size();
|
|
63 if (limit == 0) {
|
|
64 while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
|
|
65 resultSize--;
|
|
66 }
|
|
67 }
|
|
68 String[] result = new String[resultSize];
|
|
69 return list.subList(0, resultSize).toArray(result);
|
|
70 }
|
|
71
|
1778
|
72 // faster than String.replace()
|
|
73 public static String replace(String s,String target,String replacement) {
|
|
74 int i = s.indexOf(target);
|
|
75 if( i == -1 )
|
|
76 return s;
|
|
77 int starting = 0;
|
|
78 int n = target.length();
|
|
79 StringBuilder sb = new StringBuilder();
|
|
80 do {
|
|
81 sb.append(s,starting,i);
|
|
82 sb.append(replacement);
|
|
83 starting = i + n;
|
|
84 i = s.indexOf(target,starting);
|
|
85 } while( i != -1 );
|
|
86 sb.append(s,starting,s.length());
|
|
87 return sb.toString();
|
|
88 }
|
|
89
|
1583
|
90 }
|