剑指offer2 替换空格

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当

字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

package z_jzoffer.jz2;

import java.util.Stack;

/**
 * @author houChen
 * @date 2020/8/17 20:02
 * @Description:
 */
public class Solution2 {
    public static void main(String[] args) {
        StringBuffer str = new StringBuffer();
        str.append("We Are Happy");
        Solution2 solution2 = new Solution2();
        String s = solution2.replaceSpace(str);
        System.out.println(s);
    }

    public String replaceSpace(StringBuffer str) {
        //将空格在字符串中的开始位置 保存在一个int[]
        int[] arr = new int[100];
        int count=0;

        for(int i=0;i<str.length();i++){
            if(str.charAt(i)==' '){
                arr[count++]=i;
            }
        }

        for(int j= count-1;j>=0;j--){
            str.replace(arr[j],arr[j]+1,"%20");
        }
        return str.toString();
    }

    /*public String replaceSpace(StringBuffer str) {
        //将空格在字符串中的开始位置 保存在一个int[]
        Stack<Integer> s = new Stack<Integer>();

        for(int i=0;i<str.length();i++){
            if(str.charAt(i)==' '){
                s.push(i);
            }
        }

        while(!s.isEmpty()){
            str.replace(s.peek(),s.peek()+1,"%20");
            s.pop();
        }
        return str.toString();
    }*/
}
原文地址:https://www.cnblogs.com/houchen/p/13532643.html