-1
      sLine = sLine.replaceAll("&&", "&"); 
      sLine = sLine.replaceAll(((char)245)+"", "ő");
      sLine = sLine.replaceAll(((char)213)+"", "Ő");
      sLine = sLine.replaceAll(((char)361)+"", "ű");
      sLine = sLine.replaceAll(((char)251)+"", "ű");

これを1行だけにする方法はありますか?これは大きな文字列では非常に遅くなります。

4

3 に答える 3

5
于 2012-12-23T12:56:25.497 に答える
1

You can improve performance by using precompiled regular expressions. Under the hood String.replaceAll is going to compile and apply a regular expression for you anyway. As compilation of the regexp is relatively computationally intensive, this should improve performance when executing this code frequently.

private static final Pattern PATTERN_1 = Pattern.compile("\u00f5");
private static final Pattern PATTERN_2 = Pattern.compile(Character.toString((char) 241));

String original = new String("A" + (char) 245 + "\u00f1" + "D");
String replaced2 = PATTERN_1.matcher(original).replaceAll("B");
replaced2 = PATTERN_2.matcher(replaced2).replaceAll("C");
System.out.println(original + " -> " + replaced2);

Will print out:

A??D -> ABCD

When working with a very very long String this probably won't offer much performance over what you proposed.

As an aside: Using non UTF-8 characters in code will cause you (and your colleagues) pain down the road. You should use Unicode characters or, as you were, character decimal representations at all times.

于 2012-12-23T13:22:48.123 に答える
0
private static final String char1       = Character.toString((char) 245);
private static final String char2       = Character.toString((char) 213);
private static final String char3       = Character.toString((char) 361);
private static final String char4       = Character.toString((char) 251);

private static final Pattern PATTERN_1  = Pattern.compile(char1);
private static final Pattern PATTERN_2  = Pattern.compile(char2);
private static final Pattern PATTERN_3  = Pattern.compile(char3);
private static final Pattern PATTERN_4  = Pattern.compile(char4);

public static String replaceAccents(String sLine) {

    String replaced=sLine;

    if (replaced.contains(char1)) replaced  = PATTERN_1.matcher(replaced).replaceAll("ő");
    if (replaced.contains(char2)) replaced  = PATTERN_2.matcher(replaced).replaceAll("Ő");      
    if (replaced.contains(char3)) replaced  = PATTERN_3.matcher(replaced).replaceAll("Ű");
    if (replaced.contains(char4)) replaced  = PATTERN_4.matcher(replaced).replaceAll("ű");      

    return replaced;
}

Here is the final and fast code for that, thanks to Sean.

于 2012-12-23T14:25:17.393 に答える