Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- String word = "foobooandfoo";
- String converted = "";
- converted = word.replaceAll("[ao]", "1");
- converted = converted.replaceAll("[df]", "2");
- converted = converted.replaceAll("[n]", "3");
- public static void translate(StringBuilder str, char[] table)
- {
- for (int idx = 0; idx < str.length(); ++idx) {
- char ch = str.charAt(idx);
- if (ch < table.length) {
- ch = table[ch];
- str.setCharAt(idx, ch);
- }
- }
- }
- public static void translate(StringBuilder str, Map<Character, Character> table)
- {
- for (int idx = 0; idx < str.length(); ++idx) {
- char ch = str.charAt(idx);
- Character conversion = table.get(ch);
- if (conversion != null)
- str.setCharAt(idx, conversion);
- }
- }
- StringBuilder result = new StringBuilder(word.length());
- for (char c : word.toCharArray()) {
- switch (c) {
- case 'a': case 'o': result.append('1'); break;
- case 'd': case 'f': result.append('2'); break;
- case 'n': result.append('3'); break;
- default: result.append(c); break;
- }
- }
- public String convert(String text)
- {
- char[] chars = new char[text.length()];
- for (int i=0; i < text.length(); i++)
- {
- char c = text.charAt(i);
- char converted;
- switch (c)
- {
- case 'a': converted = '1'; break;
- case 'o': converted = '1'; break;
- case 'd': converted = '2'; break;
- case 'f': converted = '2'; break;
- case 'n': converted = '3'; break;
- default : converted = c; break;
- }
- chars[i] = converted;
- }
- return new String(chars);
- }
- String word = "foobooandfoo";
- String converted = word.replaceAll("[ao]", "1")
- .replaceAll("[df]", "2")
- .replaceAll("[n]", "3");
- String text = "foobooandfoo";
- Pattern p = Pattern.compile("([ao])|([df])|n");
- Matcher m = p.matcher(text);
- StringBuffer sb = new StringBuffer();
- while (m.find())
- {
- m.appendReplacement(sb, "");
- sb.append(m.start(1) != -1 ? '1' :
- m.start(2) != -1 ? '2' :
- '3');
- }
- m.appendTail(sb);
- System.out.println(sb.toString());
- // usage:
- Map<String, String> replaceRules = new HashMap<String, String>();
- replaceRules.put("ao", "1");
- replaceRules.put("df", "2");
- replaceRules.put("n", "3");
- String s = replacePartsOf("foobooandfoo", replaceRules);
- // actual method
- public String replacePartsOf(String thisString, Map<String, String> withThese) {
- for(Entry<String, String> rule : withThese.entrySet()) {
- thisString = thisString.replaceAll(rule.getKey(), rule.getValue());
- }
- return thisString;
- }
Add Comment
Please, Sign In to add comment