Skip to content

Instantly share code, notes, and snippets.

@nyilmaz
Created June 9, 2014 08:35
Show Gist options
  • Save nyilmaz/fc59f1338482bb2fcd23 to your computer and use it in GitHub Desktop.
Save nyilmaz/fc59f1338482bb2fcd23 to your computer and use it in GitHub Desktop.
public static String toUrlFriendlyCS(String str) {
if(str == null) {
return null;
}
str = removePunctuationCharacters(str, " "); // todo, implement through chars array
str = removeDuplicateWhitespaces(str, " "); // todo, implement through chars array
str = str.trim();
char[] chars = new char[str.length()];
StringBuilder builder = new StringBuilder();
str.getChars(0, str.length(), chars, 0);
char charHandled = 0;
for(char c : chars) {
if(c == 46 || c == 45 || (c >= 97 && c <= 122) || (c >= 65 && c <= 90) || (c >= 48 && c <= 57)) {
builder.append(c);
} else if(c == '&') {
builder.append("ve");
} else if(c == '\u011F') {
builder.append("g");
} else if(c == '\u011E') {
builder.append("G");
} else if(c == '\u0131') {
builder.append("i");
} else if(c == '\u0130') {
builder.append("I");
} else if(c == '\u00FC') {
builder.append("u");
} else if(c == '\u00DC') {
builder.append("U");
} else if(c == '\u015F') {
builder.append("s");
} else if(c == '\u015E') {
builder.append("S");
} else if(c == '\u00F6') {
builder.append("o");
} else if(c == '\u00D6') {
builder.append("O");
} else if(c == '\u00E7') {
builder.append("c");
} else if(c == '\u00C7') {
builder.append("C");
} else if(c == ' ') {
if(charHandled != 0 && charHandled != ' ' && charHandled != '-') {
builder.append("-");
}
}
charHandled = c;
}
return builder.toString();
}
public static String removePunctuationCharacters(String container, String replacement) {
if(container == null || container.trim().equals("")) {
return container;
}
StringBuffer sb = new StringBuffer();
Matcher m = PATTERN_PUNCTUATION_CHARS.matcher(container);
while(m.find()) {
if(replacement != null) {
m.appendReplacement(sb, replacement);
} else {
m.appendReplacement(sb, "");
}
}
m.appendTail(sb);
return sb.toString();
}
public static String removeDuplicateWhitespaces(String container, String replacement) {
if(container == null || container.trim().equals("")) {
return container;
}
StringBuffer sb = new StringBuffer();
Matcher m = PATTERN_DUPLICATE_WHITESPACE.matcher(container);
while(m.find()) {
if(replacement != null) {
m.appendReplacement(sb, replacement);
} else {
m.appendReplacement(sb, "");
}
}
m.appendTail(sb);
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment