StringUtility
/**
* Topic: Strings and Things
* $Project$ StringUtility.java
*/
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URLEncoder;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* String Utilities Topic: Pattern Matching with Regular Expressions
*
* @see Java Cookbook
* @since Created on November 18, 2008, 8:24 PM
* @author Eric Oh
*/
public class StringUtility {
public static final String DELIMITER_BACK_SLASH = "\\";
public static final String DELIMITER_BACKSPACE = "\b";
public static final String DELIMITER_CARRIAGE_RETURN = "\r";
public static final String DELIMITER_CLOSE_BRACE = "}";
public static final String DELIMITER_CLOSE_BRACKET = "]";
public static final String DELIMITER_CLOSE_PARENTHESIS = ")";
public static final String DELIMITER_CLOSE_TAG = ">";
public static final String DELIMITER_COMMA = ",";
public static final String DELIMITER_DASH = "-";
public static final String DELIMITER_DOUBLE_QUOTE = "\"";
public static final String DELIMITER_FORM_FEED = "\f";
public static final String DELIMITER_FORWARD_SLASH = "/";
public static final String DELIMITER_NEWLINE = "\n";
public static final String DELIMITER_OPEN_BRACE = "{";
public static final String DELIMITER_OPEN_BRACKET = "[";
public static final String DELIMITER_OPEN_PARENTHESIS = "(";
public static final String DELIMITER_OPEN_TAG = "<";
public static final String DELIMITER_PERIOD = ".";
public static final String DELIMITER_SEMI_COLON = ":";
public static final String DELIMITER_SINGLE_QUOTE = "\'";
public static final String DELIMITER_TAB = "\t";
public static final String DELIMITER_WHITESPACE = " ";
public static final String EOLN = System.getProperty("line.separator");
public static void main(String[] args) {
int testCase = 3;
// test.setMode(test.SINGLE);
if (testCase == 0) {
StringUtility text = new StringUtility();
String output = text.replace("/", "\\", "");
}
if (testCase == 1) {
StringUtility text = new StringUtility();
String contents = "Text pattern tester for left pad, right pad, tokenize";
System.out
.println("Testing Left Pad: " + text.leftPad(contents, 5));
System.out.println("Testing Right Pad: "
+ text.rightPad(contents, 5));
}
if (testCase == 2) {
StringUtility text = new StringUtility();
String contents = "Text pattern tester for left pad, right pad, tokenize";
String[] results = text.getArray(contents, " ");
for (int i = 0; i < results.length; i++) {
System.out.println("Testing getArray " + i + " was: "
+ results[i]);
}
}
if (testCase == 3) {
String info = "<%@page import=\"com.journey.life.model.beans.EntityBean\"% @page>"
+ EOLN
+ "<%@page import=\"com.journey.life.model.beans.EntityBean\"% @page>"
+ EOLN;
System.out.println("Before:\n" + info);
StringUtility text = new StringUtility();
info = text.substituteAll("@page", "page", info);
System.out.println("Remove @:\n" + info);
info = text.substituteAll("page", "@page", info);
System.out.println("Add @:\n" + info);
}
if (testCase == 4) {
String info = "Hello Java Programmer, Developer, Architect";
StringUtility text = new StringUtility();
System.out
.println(text.substitute("Developer", "Programmer", info));
System.out.println(text.substituteAll("Developer", "Programmer",
info));
}
if (testCase == 5) {
StringUtility text = new StringUtility();
String contents = "Text pattern for trim ";
String trim = text.trim(contents);
System.out.println(trim);
}
if (testCase == 6) {
StringUtility text = new StringUtility();
String result = text.match("this 1 text contains number 2 4 5",
"\\d+");
System.out.println(result);
}
if (testCase == 8) {
String info = "Hello Java Developer";
StringUtility text = new StringUtility();
System.out
.println(text.substitute("Developer", "Programmer", info));
System.out.println(text.substituteAll("Developer", "Programmer",
info));
}
if (testCase == 9) {
String location1 = "http://localhost:8888/HomePage/content/movie.mp4";
String location2 = "OpenGL.mp4";
StringUtility text = new StringUtility();
location2 = text.toURL(location2);
System.out.println(location2);
}
}
int width = 74;
String[] delimiters = { DELIMITER_DOUBLE_QUOTE, DELIMITER_SINGLE_QUOTE,
DELIMITER_CARRIAGE_RETURN, DELIMITER_NEWLINE, DELIMITER_TAB,
DELIMITER_BACKSPACE, DELIMITER_FORM_FEED, DELIMITER_BACK_SLASH,
DELIMITER_OPEN_TAG, DELIMITER_CLOSE_TAG,
DELIMITER_OPEN_PARENTHESIS, DELIMITER_CLOSE_PARENTHESIS,
DELIMITER_OPEN_BRACKET, DELIMITER_CLOSE_BRACKET,
DELIMITER_WHITESPACE, DELIMITER_TAB, DELIMITER_COMMA,
DELIMITER_SEMI_COLON, DELIMITER_DASH, DELIMITER_OPEN_BRACE,
DELIMITER_CLOSE_BRACE, DELIMITER_FORWARD_SLASH,
DELIMITER_BACK_SLASH, DELIMITER_PERIOD };
public StringUtility() {
super();
}
public void console() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Please enter input: ");
String word = reader.readLine();
System.out.println("You entered: " + word);
} catch (IOException e) {
e.printStackTrace();
}
}
public String empty(String word) {
String empty = new String();
if (word == null) {
empty = new String();
} else if (word.trim().isEmpty()) {
empty = word.trim();
} else {
empty = word;
}
return empty;
}
public String format(String text) {
StringBuffer formatted = new StringBuffer();
if (!isEmpty(text) && text.indexOf("\n") != -1) {
// Keep Formatting
String[] array = getArray(text, "\n");
for (int i = 0; i < array.length; i++) {
if (!isEmpty(array[i])) {
formatted.append(formatLine(array[i]));
}
}
} else {
// Direct Formatting
formatted.append(formatLine(text));
}
return formatted.toString();
}
public String formatLine(String text) {
StringBuffer formatted = new StringBuffer();
int beginIndex = 0;
int endIndex = width;
while (text.length() > width) {
endIndex = beginIndex + width;
if (text.length() > width) {
String line = text.substring(beginIndex, endIndex);
text = text.substring(endIndex);
formatted.append(line + "\n");
} else {
formatted.append(text + "\n");
}
}
formatted.append(text + "\n");
return formatted.toString();
}
public String[] getArray(String line, String delimiter) {
StringTokenizer st = new StringTokenizer(line, delimiter, true);
String[] results = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (s.equals(delimiter)) {
}
results[i] = s;
i++;
}
return results;
}
/**
* Special Characters
*/
public String[] getDelimiters() {
return delimiters;
}
public boolean hasDigits(String word) {
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (Character.isDigit(ch)) {
return true;
}
}
return false;
}
public boolean hasLetters(String word) {
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (Character.isAlphabetic(ch)) {
return true;
}
}
return false;
}
public String inputConsole() {
String word = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Please enter input: ");
word = reader.readLine();
if (word.trim().isEmpty()) {
word = null;
} else {
System.out.println("You entered: " + word);
}
} catch (IOException e) {
e.printStackTrace();
}
return word;
}
public String inputConsole(String text) {
String word = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
if (text == null) {
System.out.println("Please enter input: ");
} else {
System.out.println(text);
}
word = reader.readLine();
if (word.trim().isEmpty()) {
word = null;
} else {
System.out.println("You entered: " + word);
}
} catch (IOException e) {
e.printStackTrace();
}
return word;
}
public boolean isEmpty(String word) {
boolean empty = true;
if (word == null) {
empty = true;
} else if (word.trim().isEmpty()) {
empty = true;
} else {
empty = false;
}
return empty;
}
public boolean isNumber(String input) {
boolean flag = false;
try {
Long.parseLong(input);
flag = true;
} catch (Exception e) {
flag = false;
}
return flag;
}
public boolean isDelimiter(String s) {
for (int i = 0; i < delimiters.length; i++) {
if (s != null && s.equalsIgnoreCase(delimiters[i])) {
// System.out.println("isDelimiter=" + s + ":" + delimiters[i]);
return true;
}
}
return false;
}
public String join(String text) {
String[] line = getArray(text, "\n");
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < line.length; i++) {
String token = trim(line[i]);
if (token != null) {
buffer.append(token);
}
}
return buffer.toString();
}
public String leftPad(String output, int width) {
StringBuffer text = new StringBuffer();
for (int i = 0; i < width; i++) {
text.append(" ");
}
return text.toString() + output;
}
public String leftPad(String output, int width, String pad) {
StringBuffer text = new StringBuffer();
for (int i = 0; i < width; i++) {
text.append(pad);
}
return text.toString() + output;
}
public String match(String regex, String input) {
Matcher matcher = Pattern.compile(regex).matcher(input);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
String match = matcher.group(0);
result.append(match);
}
return result.toString();
}
public String replace(String regex, String replaceText, String input) {
Matcher matcher = Pattern.compile(regex).matcher(input);
String result = matcher.replaceFirst(replaceText);
return result;
}
public String replaceAll(String regex, String replaceText, String input) {
Matcher matcher = Pattern.compile(regex).matcher(input);
String result = matcher.replaceAll(replaceText);
return result;
}
public String rightPad(String output, int width) {
StringBuffer text = new StringBuffer();
for (int i = 0; i < width; i++) {
text.append(" ");
}
return output + text.toString();
}
public String rightPad(String output, int width, String pad) {
StringBuffer text = new StringBuffer();
for (int i = 0; i < width; i++) {
text.append(pad);
}
return output + text.toString();
}
public String search(String search, String text) {
StringBuffer result = new StringBuffer();
if (text != null) {
StringBuffer sb = new StringBuffer(text);
int count = 0;
int index = 0;
boolean found = true;
while (found) {
if (sb.indexOf(search, index) != -1) {
found = true;
index = sb.indexOf(search, index);
result.append("Found: " + search + " at index " + index
+ EOLN);
index += search.length();
count++;
} else {
found = false;
}
}
result.append("Found (" + search + "): " + count + " times.");
} else {
result.append("Not found.");
}
return result.toString();
}
public String soundex(String word) {
char[] result = new char[4];
result[0] = word.charAt(0);
result[1] = result[2] = result[3] = '0';
int index = 1;
char codeLast = ' ';
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
char code = ' ';
switch (ch) {
case 'b':
case 'f':
case 'p':
case 'v':
code = '1';
break;
case 'c':
case 'g':
case 'j':
case 'k':
code = '1';
break;
case 'q':
case 's':
case 'x':
case 'z':
code = '2';
break;
case 'd':
case 't':
code = '3';
break;
case 'l':
code = '4';
break;
case 'm':
case 'n':
code = '5';
case 'r':
code = '6';
break;
default:
code = '*';
break;
}
if (code == codeLast) {
code = '*';
}
codeLast = code;
if (code != '*') {
result[index] = code;
index++;
if (index > 3) {
break;
}
}
}
return new String(result);
}
public String substitute(String search, String replace, String text) {
String substitute = new String();
StringBuffer buffer = new StringBuffer();
if (!isEmpty(text)) {
if (replace.trim().endsWith(search)) {
Scanner scanContents = new Scanner(text);
do {
String line = new String();
if (scanContents.hasNextLine()) {
line = scanContents.nextLine();
} else {
line = text;
}
System.out.print("Substitute recursive: ");
String result = substituteLine(search, replace, line);
buffer.append(result);
if (scanContents.hasNextLine()) {
buffer.append(DELIMITER_NEWLINE);
}
} while (scanContents.hasNextLine());
substitute = buffer.toString();
scanContents.close();
} else {
Scanner scanContents = new Scanner(text);
do {
String line = new String();
if (scanContents.hasNextLine()) {
line = scanContents.nextLine();
} else {
line = text;
}
//System.out.print("SubstituteLine: ");
String result = substituteLine(search, replace, line);
buffer.append(result);
} while (scanContents.hasNextLine());
substitute = buffer.toString();
scanContents.close();
}
} else {
substitute = text;
}
return substitute;
}
public String substituteAll(String search, String replace, String text) {
String substitute = new String();
if (!isEmpty(text)) {
StringBuffer buffer = new StringBuffer();
Scanner scanContents = new Scanner(text);
while (scanContents.hasNextLine()) {
String line = scanContents.nextLine();
buffer.append(substitute(search, replace, line));
if (scanContents.hasNextLine()) {
buffer.append(DELIMITER_NEWLINE);
}
}
scanContents.close();
substitute = buffer.toString();
} else {
substitute = text;
}
return substitute;
}
public String substituteDelimiter(String existingDelimiter,
String newDelimiter, String text) {
StringTokenizer st = new StringTokenizer(text, existingDelimiter, true);
StringBuffer buffer = new StringBuffer();
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.equalsIgnoreCase(existingDelimiter)) {
buffer.append(newDelimiter);
} else {
buffer.append(token);
}
}
return buffer.toString();
}
public String substituteLine(String search, String replace, String text) {
if (text != null && !text.isEmpty()) {
if (text.indexOf(search) != -1
&& search.indexOf(DELIMITER_WHITESPACE) == -1
&& text.indexOf(DELIMITER_WHITESPACE) != -1) {
// Single search word in a multiple word line
StringBuffer buffer = new StringBuffer();
Scanner scanWords = new Scanner(text);
while (scanWords.hasNext()) {
String word = scanWords.next();
if (word.indexOf(search) != -1) {
String before = word.substring(0, word.indexOf(search));
String after = word.substring(word.indexOf(search)
+ search.length());
buffer.append(before + replace + after);
} else {
buffer.append(word);
}
if (scanWords.hasNext()) {
buffer.append(DELIMITER_WHITESPACE);
}
}
scanWords.close();
text = buffer.toString();
System.out.println("SubstituteLine[1] multiple words: " + text);
} else if (text.indexOf(search) != -1) {
StringUtility stool = new StringUtility();
System.out.println(stool.isDelimiter(search) + ":" + search);
if (stool.isDelimiter(search)) {
text = substituteDelimiter(search, replace, text);
System.out
.println("SubstituteDelimiter[2] multiple words: "
+ text);
} else if (text.indexOf(search) != -1
&& text.lastIndexOf(search) != text.indexOf(search)) {
StringBuffer buffer = new StringBuffer();
Scanner scanWords = new Scanner(text);
while (scanWords.hasNext()) {
String word = scanWords.next();
if (word.indexOf(search) != -1) {
String before = word.substring(0,
word.indexOf(search));
String after = word.substring(word.indexOf(search)
+ search.length());
buffer.append(before + replace + after);
} else {
buffer.append(word);
}
if (scanWords.hasNext()) {
buffer.append(DELIMITER_WHITESPACE);
}
}
scanWords.close();
text = buffer.toString();
System.out.println("SubstituteLine[3] multiple words: "
+ text);
} else {
// Single search word replacement
String before = text.substring(0, text.indexOf(search));
String after = text.substring(text.indexOf(search)
+ search.length());
text = before + replace + after;
System.out.println("SubstituteLine[4] single words: "
+ text);
}
} else {
// No word replacement
System.out.println("SubstituteLine same result: " + text);
}
}
return text;
}
public String toCamelCase(String source) {
if (source != null) {
StringBuffer buffer = new StringBuffer();
StringTokenizer st = new StringTokenizer(source, "_");
while (st.hasMoreTokens()) {
String token = st.nextToken();
token = Character.toUpperCase(token.charAt(0))
+ token.substring(1).toLowerCase();
buffer.append(token);
}
if (!isEmpty(buffer.toString())) {
source = buffer.toString();
}
// System.out.println(source);
}
return source;
}
public String toSentenceCase(String source) {
if (source != null) {
StringBuffer buffer = new StringBuffer();
StringTokenizer st = new StringTokenizer(source, "_");
while (st.hasMoreTokens()) {
String token = st.nextToken();
token = Character.toUpperCase(token.charAt(0))
+ token.substring(1);
buffer.append(token);
}
if (!isEmpty(buffer.toString())) {
source = buffer.toString();
}
// System.out.println(source);
}
return source;
}
public String toString(ByteArrayOutputStream bos) {
String data = null;
if (bos == null) {
bos = new ByteArrayOutputStream();
} else {
PrintStream out = new PrintStream(bos);
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
data = bos.toString();
}
return data;
}
public String toTitleCase(String source) {
return Character.toUpperCase(source.charAt(0))
+ source.substring(1).toLowerCase();
}
@SuppressWarnings("deprecation")
public String toURL(String location) {
StringBuffer url = new StringBuffer();
if (location != null && location.length() > 0) {
if (location.indexOf("/") != -1) {
String address = location.substring(0,
location.lastIndexOf("/") + 1);
String filename = location
.substring(location.lastIndexOf("/") + 1);
filename = URLEncoder.encode(filename);
// System.out.println(address);
// System.out.println("Before:" + filename);
filename = substituteAll("+", "%20", filename);
// System.out.println("After:" + filename);
url.append(address);
url.append(filename);
} else {
url.append(location);
}
}
return url.toString();
}
public String trim(String word) {
if (word == null) {
} else if (word.trim().isEmpty()) {
word = null;
} else {
word = word.trim();
}
return word;
}
}