牛客网剑指offer-替换空格

来源:互联网 发布:java经典书籍 编辑:程序博客网 时间:2024/06/08 19:00
package www.niuke.offer;/* * 请实现一个函数,将一个字符串中的空格替换成“%20”。 * 例如,当字符串为We Are Happy. * 则经过替换之后的字符串为We%20Are%20Happy。 */public class test02 {public String replaceSpace(StringBuffer str) {int len = str.length();// 字符串的长度int count = 0;// 字符串中的空格的个数for (int i = 0; i < len; i++) {if (str.charAt(i) == ' ')count++;}int newlen = len + 2 * count;int index = newlen - 1;char[] ptr = new char[newlen];while (len > 0) {if (str.charAt(len - 1) != ' ') {ptr[index--] = str.charAt(len - 1);} else {ptr[index--] = '0';ptr[index--] = '2';ptr[index--] = '%';}--len;}return new String(ptr);}public static void main(String[] args) {String s = "We Are Happy";StringBuffer str = new StringBuffer(s);System.out.println(new test02().replaceSpace(str));}}

原创粉丝点击