Mercurial Hosting > luan
view src/goodjava/util/GoodUtils.java @ 1804:b4328322d2be
minor
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Tue, 07 May 2024 22:08:37 -0600 |
parents | 1725fdb6c4f5 |
children |
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); } // faster than String.replace() public static String replace(String s,String target,String replacement) { int i = s.indexOf(target); if( i == -1 ) return s; int starting = 0; int n = target.length(); StringBuilder sb = new StringBuilder(); do { sb.append(s,starting,i); sb.append(replacement); starting = i + n; i = s.indexOf(target,starting); } while( i != -1 ); sb.append(s,starting,s.length()); return sb.toString(); } }