Write a method to replace all spaces in a string with ‘%20’.
/**
* InterTest
* cn.ustc.inter.array_string
* ReplaceSpace.java
* @version 1.0.0
* 2012-4-11 下午1:52:36
* Copyright (c) ustcxjt
*
*/
package cn.ustc.inter.array_string;
import java.util.ArrayList;
/**
*
* ReplaceSpace
*
* Author:ustcxjt Modify by ustcxjt Date:2012-4-11 下午1:52:36
*
* @version 1.0.0
*
*/
public class ReplaceSpace {
public static char[] ReplaceFun(char[] str) {
System.out.println(str);
ArrayList<Character> tmp = new ArrayList<Character>();
int i = 0;
for (char ch : str) {
if (ch == ' ') {
tmp.add('%');
tmp.add('2');
tmp.add('0');
i++;
} else {
tmp.add(ch);
}
}
char[] re = new char[str.length + 2 * i + 1];
for (i = 0; i < tmp.size(); i++) {
re[i] = tmp.get(i);
}
return re;
}
/**
* main(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
*
* @param args
* void
* @exception
* @since 1.0.0
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "a aaa aabbbbddd fff ";
System.out.println(ReplaceSpace.ReplaceFun(str.toCharArray()));
}
}
ArrayList<Character> tmp转换成字符数组
使用tmp.toString().toCharArray()
System.out.println(tmp.toString().toCharArray());
输出
[a, %, 2, 0, a, a, a, %, 2, 0, a, a, b, b, b, b, d, d, d, %, 2, 0, f, f, f, %, 2, 0]
不是想要的结果
于是采用了
for (i = 0; i < tmp.size(); i++) {
re[i] = tmp.get(i);
}
谁有不用重新遍历的方法
请告诉我