Please implement a function to replace spaces in a string with "%20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.
Replace in reverse order to reduce time complexity
StringOnce initialized, it cannot be changed.
Use StringBuffer because of Niuke.com’s template.
In actual use, it is recommended to use StringBuilder for single threads because it is lock-free and highly efficient.
In multi-threading, use StringBuffer.
The built-in functions of both are the same
Change the original string or create a new string (if it is original, you need to reset the length setLength())
Do not consider using the existing replace()
public static String replaceSpace(StringBuffer str){ int length = str.length(); int spacenum = 0; //统计空格字符个数 for(int i=0;i<length;i++){ if(str.charAt(i) == ' ') spacenum++; } int lengthNew = length + spacenum*2; str.setLength(lengthNew); int index = length-1; int indexNew = lengthNew-1; for(;index>=0;index--){ if(str.charAt(index) == ' '){ str.setCharAt(indexNew--, '0'); str.setCharAt(indexNew--, '2'); str.setCharAt(indexNew--, '%'); } else{ str.setCharAt(indexNew--, str.charAt(index)); } } return str.toString(); }
Okay, that’s it for this article. Welcome to give me your advice. If you are interested, please study php Chinese websiteonline java video tutorial
The above is the detailed content of Java implements ideas and codes for replacing spaces in strings. For more information, please follow other related articles on the PHP Chinese website!