因为要去除一个字符串中的所有空格,没有找到现成可用的方法,所以写了一下.
比较下来,removeChar和removeChar2的执行效率时间为 5:8. 可能是因为removeChar2中,创建了更多的对象的缘故?
package all;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DateTest {
/**
* Logger for this class
*/
private static final Log logger = LogFactory.getLog(DateTest.class);
public static void main(String[] args) {
String text=" a bc d efghijkl mn opq rst uvwxyz ";
logger.info(removeChar(text, ' '));
long begin=System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
removeChar(text, ' ');
}
logger.info(System.currentTimeMillis()-begin);
begin=System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
removeChar2(text, ' ');
}
logger.info(System.currentTimeMillis()-begin);
}
public static String removeChar(String str,char c){
char[] array=str.toCharArray();
int lastIndex=0;
int length=array.length;
for (int i = 0; i < length; i++) {
char value=array[i];
if(value!=c){
if(lastIndex<i){
array[lastIndex]=value;
array[i]=c;
}
lastIndex++;
}
}
return new String(array,0,lastIndex);
}
public static String removeChar2(String str,char c){
StringBuilder builder=new StringBuilder();
char[] array=str.toCharArray();
for (int i = 0; i < array.length; i++) {
char value=array[i];
if(value!=c){
builder.append(c);
}
}
return builder.toString();
}
}
比较下来,removeChar和removeChar2的执行效率时间为 5:8. 可能是因为removeChar2中,创建了更多的对象的缘故?
package all;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DateTest {
/**
* Logger for this class
*/
private static final Log logger = LogFactory.getLog(DateTest.class);
public static void main(String[] args) {
String text=" a bc d efghijkl mn opq rst uvwxyz ";
logger.info(removeChar(text, ' '));
long begin=System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
removeChar(text, ' ');
}
logger.info(System.currentTimeMillis()-begin);
begin=System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
removeChar2(text, ' ');
}
logger.info(System.currentTimeMillis()-begin);
}
public static String removeChar(String str,char c){
char[] array=str.toCharArray();
int lastIndex=0;
int length=array.length;
for (int i = 0; i < length; i++) {
char value=array[i];
if(value!=c){
if(lastIndex<i){
array[lastIndex]=value;
array[i]=c;
}
lastIndex++;
}
}
return new String(array,0,lastIndex);
}
public static String removeChar2(String str,char c){
StringBuilder builder=new StringBuilder();
char[] array=str.toCharArray();
for (int i = 0; i < array.length; i++) {
char value=array[i];
if(value!=c){
builder.append(c);
}
}
return builder.toString();
}
}