我正在尝试从给定主机访问所有可能的子域。我写了以下代码。它有效,但我唯一担心的是性能。
是否需要进一步优化这段代码:
import java.util.Arrays;
import java.util.Collections;
public class DemoExtractHostArray {
public static String[] createHostArray(String host) {
String[] stringArr = host.split("\\.");
String[] hostArray = new String[stringArr.length];
int hostIndex = 0;
for(int index = stringArr.length-1; index>=0;index--){
if(hostIndex==0){
hostArray[hostIndex] = stringArr[index];
}
else{
hostArray[hostIndex] = stringArr[index]+"."+hostArray[hostIndex-1];
}
hostIndex++;
}
Collections.reverse(Arrays.asList(hostArray));
return hostArray;
}
public static void main(String a[]){
for(String s: createHostArray("a.b.c.d.e.f")){
System.out.println(s);
}
}
}
输出:
a.b.c.d.e.f
b.c.d.e.f
c.d.e.f
d.e.f
e.f
f
最佳答案
您的代码唯一可能的改进是删除此调用:
Collections.reverse(Arrays.asList(hostArray));
由于您正在创建 hostArray
然后将其反转,您不妨更改循环以立即以相反的顺序创建数组,从而不再需要显式反转:
// hostIndex is no longer required - remove the line below:
// int hostIndex = 0;
for(int index = stringArr.length-1 ; index>=0 ; index--){
if(index == stringArr.length-1) {
hostArray[index] = stringArr[index];
}
else{
hostArray[index] = stringArr[index]+"."+hostArray[index+1];
}
}
关于java - 优化字符串操作代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21264456/