Mercurial Hosting > luan
view src/goodjava/util/GoodUtils.java @ 1728:30df07a9771c
minor
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Tue, 30 Aug 2022 21:59:51 -0600 |
parents | 2f4c99c02436 |
children | 1725fdb6c4f5 |
line wrap: on
line source
package goodjava.util; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.ArrayList; public final class GoodUtils { public static byte[] getBytes(String s,String charsetName) { try { return s.getBytes(charsetName); } catch(UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static String base64Encode(String s) { return Base64.getEncoder().encodeToString(getBytes(s,"UTF-8")); } public static String[] split(String s,String splitter) { return split(s,splitter,-1); } // modified from String.java public static String[] split(String s,String splitter,int limit) { int len = s.length(); int n = splitter.length(); int off = 0; int next = 0; boolean limited = limit > 0; ArrayList<String> list = new ArrayList<>(); if( n==0 ) { limit = limited ? Math.min(limit,len) : len; for( int i=0; i<limit; i++ ) { list.add(s.substring(i, i+1)); } String[] result = new String[limit]; return list.toArray(result); } while ((next = s.indexOf(splitter, off)) != -1) { if (!limited || list.size() < limit - 1) { list.add(s.substring(off, next)); off = next + n; } else { // last one //assert (list.size() == limit - 1); list.add(s.substring(off, len)); off = len; break; } } // If no match was found, return s if (off == 0) return new String[]{s}; // Add remaining segment if (!limited || list.size() < limit) list.add(s.substring(off, len)); // Construct result int resultSize = list.size(); if (limit == 0) { while (resultSize > 0 && list.get(resultSize - 1).length() == 0) { resultSize--; } } String[] result = new String[resultSize]; return list.subList(0, resultSize).toArray(result); } }