How to rewrite this block of code using StringBuilder in Java?

Given the word, I have to replace some specific alphabets with some specific letters, such as 1 for a, 5 for b, etc. I am using regex for this. I understand that StringBuilder is the best way to deal with this problem, as I am doing a lot of string manipulations. That's what I'm doing:

String word = "foobooandfoo";
String converted = "";
converted = word.replaceAll("[ao]", "1");
converted = converted.replaceAll("[df]", "2");
converted = converted.replaceAll("[n]", "3");

My problem is how to rewrite this program using StringBuilder. I tried everything, but I can not succeed. Or is using String enough for this?

+3
source share
9 answers

I think this is a case where clarity and performance coincide happily. I would use a lookup table to do a "translation".

  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);
      }
    }
  }

str , , :

  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 ( , ).

+8

, , . Matcher, :

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;
    }
}
+2

, StringBuilder . Matcher, regex java , , .

+1

, . API, , String StringBuilder.

char char, - :

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);
}

, , .

+1

StringBuilder StringBuffer . : http://www.thectoblog.com/2011/01/stringbuilder-vs-stringbuffer-vs.html , .

. , , , .

String. , gc , .

P Arrayah, LinkedHashMap -, , .

Map replaceRules = new HashMap();

Map replaceRules = new LinkedHashMap();

+1

Matcher.replaceAll(), , String. , , , . .

: !

0

, StringBuilder - , .

? - , , , StringBuilder. StringBuilder - , .

"", .

, :

String word = "foobooandfoo";
String converted = word.replaceAll("[ao]", "1")
                       .replaceAll("[df]", "2")
                       .replaceAll("[n]", "3");

StringBuilder,

java.util.regex.Pattern # (java.lang.CharSequence)

CharSequence ( StringBuilder). . http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#matcher(java.lang.CharSequence).

0

StringBuilder vs. regex - . , String # replaceAll() , , , , . , Matcher replaceAll(), :

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());

, ; , .

0

- , , . -

// 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;
}

and after you succeed, reorganize it instead of using arrays of characters. Although I think that what you want to do can be done using StringBuilder, most likely it will not be worth the effort.

-2
source

Source: https://habr.com/ru/post/1699425/


All Articles