替换空格

来源:互联网 发布:庞博 程序员 编辑:程序博客网 时间:2024/05/18 03:06

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

时间限制:1秒空间限制:32768K热度指数:366241
 
package nowcoder;public class no2 {public static String replaceSpace(StringBuffer str) {    String str1=str.toString();    int len=str1.length();    int count=0;    for(int i=0;i<len;i++)    {    if(str1.charAt(i)==' ')    count++;    }    int newlen=len+2*count;    char[] p=new char[newlen];    int i=0;    while(i<newlen)    {    for(int j=0;j<len;j++)    {    if(str1.charAt(j)!=' ')    {    p[i]=str1.charAt(j);    i++;    }    else{    p[i++]='%';    p[i++]='2';    p[i++]='0';    }    }    }    String str2 = String.valueOf(p);    return str2;    }public static void main(String[] args){StringBuffer stringBuffer=new StringBuffer("we are happy");System.out.println(replaceSpace(stringBuffer));}}

输出为:we%20are%20happy



原创粉丝点击