comparison src/goodjava/util/GoodUtils.java @ 1720:2f4c99c02436

add GoodUtils.split
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 25 Jul 2022 17:31:50 -0600
parents 1cc6c7fa803d
children 1725fdb6c4f5
comparison
equal deleted inserted replaced
1719:2f3a8f16f583 1720:2f4c99c02436
1 package goodjava.util; 1 package goodjava.util;
2 2
3 import java.io.UnsupportedEncodingException; 3 import java.io.UnsupportedEncodingException;
4 import java.util.Base64; 4 import java.util.Base64;
5 import java.util.ArrayList;
5 6
6 7
7 public final class GoodUtils { 8 public final class GoodUtils {
8 9
9 public static byte[] getBytes(String s,String charsetName) { 10 public static byte[] getBytes(String s,String charsetName) {
15 } 16 }
16 17
17 public static String base64Encode(String s) { 18 public static String base64Encode(String s) {
18 return Base64.getEncoder().encodeToString(getBytes(s,"UTF-8")); 19 return Base64.getEncoder().encodeToString(getBytes(s,"UTF-8"));
19 } 20 }
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
20 } 72 }