且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何连接在Java中的字符串数组

更新时间:2023-11-07 11:27:46

暂且不论事情像检查,如果一个数组是,你可以为它创建一个一般方法和用它在你的具体情况,如:

 公共字符串[] concatAll(字符串[] jobsA,字符串[] jobsB,字符串[] jobsC,字符串[] jobsD)
    {
        返回generalConcatAll(jobsA,jobsB,jobsC,jobsD);
    }    公众的String [] generalConcatAll(字符串[] ...作业){
        INT LEN = 0;
        对于(最终的String []的工作:作业){
            LEN + = job.length;
        }        最终的String []结果=新的String [LEN]        INT currentPos = 0;
        对于(最终的String []的工作:作业){
            System.arraycopy(工作,为0,因此,currentPos,job.length);
            currentPos + = job.length;
        }        返回结果;
    }

I'm wondering how I can concatenate 4 string arrays in Java.

There is a question about this already. How to concatenate two arrays in Java?

But I tried to replicate it but it does not work for me.

This is what my code looks like:

Calling the method:

concatAll(jobs1, jobs2, jobs3, jobs4);

The method itself:

public String[] concatAll(String[] jobsA, String[] jobsB, String[] jobsC, String[] jobsD) {
    int totalLength = jobsA.length;
    for (String[] array : jobsD) {
        totalLength += array.length;
    }

    String[] result = Arrays.copyOf(jobsA, totalLength);

    int offset = jobsA.length;

    for (String[] array : jobsD) {
        System.arraycopy(array, 0, result, offset, array.length);
        offset += array.length;
    }
    return result;
}

Putting aside things like checking if an array is null, you can create a general method for it and use it in your specific case, like this:

    public String[] concatAll(String[] jobsA, String[] jobsB, String[] jobsC, String[] jobsD) 
    {
        return generalConcatAll (jobsA, jobsB, jobsC, jobsD);
    }

    public String[] generalConcatAll(String[]... jobs) {
        int len = 0;
        for (final String[] job : jobs) {
            len += job.length;
        }

        final String[] result = new String[len];

        int currentPos = 0;
        for (final String[] job : jobs) {
            System.arraycopy(job, 0, result, currentPos, job.length);
            currentPos += job.length;
        }

        return result;
    }