题解 | #替换空格#

替换空格

http://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68

字符串中空格的替换

方法1 临时数组
创建临时数组,用于存放原字符串的复制与替换结果
注:1.创建的临时数组大小取最大值即原字符串数组大小的三倍
2.创建索引 index ,这样每次赋值只需要将index自加即可,例如 c[index++] = '%';
3.寻找字符串中特定位字符方法: char c0 = s.charAt(i);
4.将字符数组转化为字符串的方法: String newStr = new String(c, 0, index);

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    public String replaceSpace (String s) {
        // write code here
        int length = s.length();
        char[] c = new char[3*length];
        int index = 0;
        for(int i=0; i<length; i++){
            char c0 = s.charAt(i);
            if(c0 == ' '){
                c[index++] = '%';
                c[index++] = '2';
                c[index++] = '0';
            }
            else{
                c[index++] = c0;
            }
        }
        String newStr = new String(c, 0, index);
        return newStr;
    }
}
全部评论

相关推荐

10-17 17:54
门头沟学院 Java
点赞 评论 收藏
分享
在看牛客的社畜很积极:身高体重那一行信息去掉,学校那一行的信息放上面,找半天都没找到你是哪个学校什么专业的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务