Skip to content

Instantly share code, notes, and snippets.

@sahirshahryar
Created June 14, 2013 11:18
Show Gist options
  • Save sahirshahryar/5781095 to your computer and use it in GitHub Desktop.
Save sahirshahryar/5781095 to your computer and use it in GitHub Desktop.
String math. We already have algebra (math with letters), so why not just math with words? NOTE: Untested, will test later.
package com.futuredev.tracker.msg;
import java.util.ArrayList;
public class StringMath {
// "Multiplies" a string.
public static String multiply (String start, int times, String separator) {
String result = "";
boolean first = true;
for (int i = 0; i < times; i++) {
result += (first ? "" : separator) + start;
first = false;
} return result;
}
// Divides a string into an array.
public static String[] divide (String start, int denominator) {
ArrayList<String> parts = new ArrayList<String>();
boolean evenlyDivisible = start.length() % denominator == 0;
if (evenlyDivisible) {
int quotient = start.length() / denominator;
for (int i = 0; i < denominator; i++) {
int start = i * quotient;
int finish = start + quotient - 1;
parts.add(start.substring(start, finish));
}
} else {
int quotient = start.length() / denominator;
int offset = 0;
for (int i = 0; i < denominator; i++) {
boolean even = i % 2 == 0;
int start = (i * quotient) + offset;
int finish = start + denominator;
parts.add(start.substring(start, finish));
if (!even) ++offset;
}
}
return (String[]) parts.toArray();
}
// Loops the characters of a string.
public static String loop (String start, int chars) {
if (chars > start.length()) {
int x = chars;
while (chars > start.length()) {
x -= start.length();
}
int times = chars / start.length() + (chars % start.length() == 0 ? 0 : 1);
String result = "";
for (int i = 0; i < times; i++) {
result += (times - i == 1 ? start.substring(0, x) : start);
} return result;
} String addition = start.substring(0, chars);
return start + addition;
}
// Trims a string.
public static String trim (String start, int length) {
return (length >= start.length() ? start : start.substring(0, length));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment