剑指offer 4. 替换空格

来源:互联网 发布:犀牛5.0mac 编辑:程序博客网 时间:2024/06/03 07:27
// 题目:输入一个字符串,用%20替换空格// 解法:使用StringBuffer完成public class Main {public static void main(String[] args) throws Exception {String result = replaceBlank2("we as as");System.out.println(result);}//使用StringBuffer的方法public static String replaceBlank(String str){StringBuffer sb = new StringBuffer();for(int i = 0;i<str.length();i++){if(str.charAt(i) == ' '){sb.append("%20");}else{sb.append(str.charAt(i));}}return new String(sb);}//不使用StringBuffer的方法,原理相同public static String replaceBlank2(String str){int countOfBlank = 0;for(int i = 0;i<str.length();i++){if(str.charAt(i) == ' '){countOfBlank++;//统计空格的数目}}char[] result = new char[str.length()-countOfBlank+3*countOfBlank];//将结果设置为适合的长度int newIndex = 0;for(int i = 0;i<str.length();i++){//根据原字符串相应位置是否是空格建立新的字符串if(str.charAt(i) == ' '){result[newIndex++] = '%';result[newIndex++] = '2';result[newIndex++] = '0';}else{result[newIndex++]  = str.charAt(i);}}return new String(result);}}

原创粉丝点击