changeset 1720:2f4c99c02436

add GoodUtils.split
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 25 Jul 2022 17:31:50 -0600
parents 2f3a8f16f583
children 5c69d2e8bd75
files conv.txt src/goodjava/util/GoodUtils.java
diffstat 2 files changed, 53 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/conv.txt	Mon Jul 25 14:31:48 2022 -0600
+++ b/conv.txt	Mon Jul 25 17:31:50 2022 -0600
@@ -5,6 +5,7 @@
 String.gsub
 String.match
 String.matches
+String.split
 
 String.contains
 String.starts_with
--- a/src/goodjava/util/GoodUtils.java	Mon Jul 25 14:31:48 2022 -0600
+++ b/src/goodjava/util/GoodUtils.java	Mon Jul 25 17:31:50 2022 -0600
@@ -2,6 +2,7 @@
 
 import java.io.UnsupportedEncodingException;
 import java.util.Base64;
+import java.util.ArrayList;
 
 
 public final class GoodUtils {
@@ -17,4 +18,55 @@
 	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);
+	}
+
 }