String: How to replace multiple possible characters with a single character?

后端 未结 3 1765
野趣味
野趣味 2020-12-25 10:11

I would like to replace all \'.\' and \' \' with a \'_\'

but I don\'t like my code...

is there a more efficient way to

相关标签:
3条回答
  • 2020-12-25 10:38

    s.replaceAll("[\\s\\.]", "_")

    0 讨论(0)
  • 2020-12-25 10:45
    String new_s = s.toLowerCase().replaceAll("[ .]", "_");
    

    EDIT:

    replaceAll is using regular expressions, and using . inside a character class [ ] just recognises a . rather than any character.

    0 讨论(0)
  • 2020-12-25 10:50

    Use String#replace() instead of String#replaceAll(), you don't need regex for single-character replacement.

    I created the following class to test what's faster, give it a try:

    public class NewClass {
    
        static String s = "some_string with spaces _and underlines";
        static int nbrTimes = 10000000;
    
        public static void main(String... args) {
    
            long start = new Date().getTime();
            for (int i = 0; i < nbrTimes; i++)
                doOne();
            System.out.println("using replaceAll() twice: " + (new Date().getTime() - start));
    
    
    
            long start2 = new Date().getTime();
            for (int i = 0; i < nbrTimes; i++)
                doTwo();
            System.out.println("using replaceAll() once: " + (new Date().getTime() - start2));
    
            long start3 = new Date().getTime();
            for (int i = 0; i < nbrTimes; i++)
                doThree();
            System.out.println("using replace() twice: " + (new Date().getTime() - start3));
    
        }
    
        static void doOne() {
            String new_s = s.toLowerCase().replaceAll(" ", "_").replaceAll(".", "_");
        }
    
        static void doTwo() {
            String new_s2 = s.toLowerCase().replaceAll("[ .]", "_");
        }
    
        static void doThree() {
            String new_s3 = s.toLowerCase().replace(" ", "_").replace(".", "_");
        }
    }
    

    I get the following output:

    using replaceAll() twice: 100274

    using replaceAll() once: 24814

    using replace() twice: 31642

    Of course I haven't profiled the app for memory consumption, that might have given very different results.

    0 讨论(0)
提交回复
热议问题