Last active
August 29, 2015 14:06
-
-
Save sagan/d438272916374f99b152 to your computer and use it in GitHub Desktop.
Java 版本的 php strtr 函数 ( replace 是 Map<String, String> 模拟的关联数组 ) / Java version of php "strtr" function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fuck.you.java; | |
import java.util.*; | |
public class Strtr { | |
/* | |
from php strtr | |
*/ | |
static public String strtr(String str, Map<String, String> replace_arr) { | |
int maxlen = 0; int minlen = 1024*128; | |
if ( replace_arr == null || replace_arr.size() == 0 ) return str; | |
for(String key : replace_arr.keySet()) { | |
int len = key.length(); | |
if( len < 1 ) continue; | |
if( len > maxlen ) maxlen = len; | |
if( len < minlen ) minlen = len; | |
} | |
int len = str.length(); | |
int pos = 0; String result = ""; | |
while( pos < len ) { | |
if( pos + maxlen > len ) maxlen = len - pos; | |
boolean found = false; String key = ""; | |
for(int i = 0; i < maxlen; ++i) key += str.charAt(i + pos); | |
for(int i = maxlen; i >= minlen; --i) { | |
String key1 = key.substring(0, i); | |
if( replace_arr.containsKey(key1) ) { | |
result += replace_arr.get(key1); | |
pos += i; | |
found = true; | |
break; | |
} | |
} | |
if( ! found ) result += str.charAt(pos++); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment