Home > Java > javaTutorial > body text

Java implements ideas and codes for replacing spaces in strings

PHPz
Release: 2017-04-23 14:53:41
Original
2520 people have browsed it

Problem description:

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.

Basic idea of ​​​​replacing spaces in strings in java:

Replace in reverse order to reduce time complexity

Implementation plan:

  • 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

Thinking:

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

Java implements the code to replace spaces in a string:

public static String replaceSpace(StringBuffer str){        
        int length = str.length();        int spacenum = 0;        
        //统计空格字符个数
        for(int i=0;i<length;i++){            if(str.charAt(i) == &#39; &#39;)
                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) == &#39; &#39;){
                str.setCharAt(indexNew--, &#39;0&#39;);
                str.setCharAt(indexNew--, &#39;2&#39;);
                str.setCharAt(indexNew--, &#39;%&#39;);
            }            else{
                str.setCharAt(indexNew--, str.charAt(index));
            }
        }        return str.toString();
    }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!