剑指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);}}
阅读全文
0 0
- 4.替换空格||剑指offer
- 剑指offer 4. 替换空格
- [剑指offer]替换空格
- [剑指offer]替换空格
- 剑指offer:替换空格
- 替换空格--《剑指offer》
- 剑指Offer:替换空格
- 【剑指offer】替换空格
- 《剑指Offer》--替换空格
- 剑指offer--替换空格
- 【剑指offer】替换空格
- 【剑指offer】空格替换
- 剑指offer-替换空格
- 剑指offer:替换空格
- [剑指offer]替换空格
- 《剑指offer》替换空格
- 剑指offer:替换空格
- 【剑指Offer】替换空格
- mysql 主从同步备份
- Linq学习总结之查询运算符笔记
- Docker网络连接探索
- jQuery Validate 无法验证 chosen-select元素
- 《UNIX环境高级编程中文版》pdf
- 剑指offer 4. 替换空格
- Oracle表访问方式
- Scala spark 报错
- 继承中的构造方法
- 2017.5.14测试 第1题: 无限剑制
- MySQL Cluster (五) --- 动态增加数据节点配置步骤
- IE8支持css3选择器
- 算术表达式求值
- Linux下highcharts导出图片乱码问题