Top 150 Questions - 1.5

来源:互联网 发布:工程设计优化方法手段 编辑:程序博客网 时间:2024/05/04 12:29

1.5 Write a method to replace all spaces in a string with ‘%20’.

package Question1_5;public class Question1_5{public static void main(String[] args){Question1_5 q = new Question1_5();System.out.println(q.ReplaceSpace(new String("abcdef").toCharArray()));System.out.println(q.ReplaceSpace(new String("abc d e f").toCharArray()));System.out.println(q.ReplaceSpace(new String(" ").toCharArray()));System.out.println(q.ReplaceSpace(new String("  ").toCharArray()));}public char[] ReplaceSpace(char[] str){// considering the worst case, where all the elements are space, we must have an array whose// size is three times the input array size. If memory size is a main consideration, we can// first compute the  number of spaces. char[] strClone = new char[str.length * 3 + 1];int i, j;for (i = 0, j = 0; i < str.length; i++){if (str[i] != ' ')strClone[j++] = str[i];else{strClone[j++] = '%';strClone[j++] = '2';strClone[j++] = '0';}}// j is at the end of strClonestrClone[j] = '\0';return strClone;}}