java - 优化字符串操作代码

标签 java string

我正在尝试从给定主机访问所有可能的子域。我写了以下代码。它有效,但我唯一担心的是性能。

是否需要进一步优化这段代码:

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/

相关文章:

c - 如何返回一个字符串地址,然后将其分配给一个新的字符串?

java - 如何在jsf/myfaces中创建指定时间段的日历?是否可以?

java - JCSMP 安慰连接

php - 相当于 PHP 字符串附加的 JavaScript

ruby - 无效的十六进制转义

python - Pandas 在另一个系列的一个系列中找到 super 字符串

java - 应该在列表本身还是在锁定对象上进行同步?

java - 将对象从 java 传输到 C#

java - 代理已创建 JMS

java - PHP数组输出