Some records about Java strings (substitute space in sword offer)


Please implement a function to replace each space in a string with "% 20". For example, when the string is We Are Happy. The string after replacement is We% 20Are% 20Happy.


Precautions:

  1.  The value of String is immutable, which leads to the creation of a new String object every time you operate on String, which is not only inefficient, but also wastes a lot of limited memory space; when modifying the string, you need to use StringBuffer StringBuilder class.
  2. Unlike the String class, objects of the StringBuffer and StringBuilder classes can be modified multiple times, and no new unused objects are generated. The StringBuilder class was introduced in Java 5. The biggest difference between it and StringBuffer is that the StringBuilder method is not thread-safe (cannot be accessed synchronously). Because StringBuilder has a speed advantage over StringBuffer, it is recommended to use the StringBuilder class in most cases. However, in applications where thread safety is required, the StringBuffer class must be used.
  3. Note that the char chatAt (ingt index) method in StringBuffer is used to return the character at the specified index.
  4. Note: The java string does not end with '\ 0', while c or c ++ ends with '\ 0'.
  5. Problem-solving ideas:在当前字符串替换,怎么替换才更有效率(不考虑java里现有的replace方法)。从前往后替换,后面的字符要不断往后移动,要多次移动,所以效率低下从后往前,先计算需要多少空间,然后从后往前移动,则每个字符只为移动一次,这样效率更高一点 

 public String replaceSpace(StringBuffer str) {
        if(str==null)
            return null;
        int oldnum = str.length();
        int countblank = 0;
        for(int i=0;i<oldnum;i++){
            if(str.charAt(i)==' '){
                countblank++;
            }
        }
        int newlength = oldnum + countblank*2;
        str.setLength(newlength);
        int pnewlength = newlength -1;//Java字符串结尾没有'/0'
        for (int j = oldnum-1;j >= 0;j--){
            if(str.charAt(j)==' '){
                str.setCharAt(pnewlength--,'0');
                str.setCharAt(pnewlength--,'2');
                str.setCharAt(pnewlength--,'%');
            }else{
                str.setCharAt(pnewlength,str.charAt(j));
                pnewlength--;
            }
        }
        return str.toString();
    }

 

Published 9 original articles · Likes0 · Visits 250

Guess you like

Origin blog.csdn.net/Fabri/article/details/105166301