copy only portion of char[] into String

2019-04-27 03:17发布

I have an array char[] ch. My question is the following. How can I merge values from ch[2] to ch[7] into a String? I would like to achieve this without looping through the char array. Any suggestions?

Thanks for taking the time to answer my question.

标签: java string char
3条回答
混吃等死
2楼-- · 2019-04-27 03:50

Use new String(value, offset, count), reference.

Where offset is the starting index and count is your index difference. In your case, it's 7-2=5.

Obviously, value is your character array.

查看更多
该账号已被封号
3楼-- · 2019-04-27 04:03

Try this:

        char[] left = new char[]{'l','e','f','t'};
        char[] right = new char[]{'r','i','g','h','t'};
        char[] merge = new char[left.length + right.length]; 
        System.arraycopy(left, 0, merge, 0, left.length);
        System.arraycopy(right, 0, merge, left.length, right.length);
        String mergeString = new String(merge);
        System.out.println(mergeString);

Output:

leftright

查看更多
Lonely孤独者°
4楼-- · 2019-04-27 04:07

You can use one of the other constructors for String

There is one that takes a char array, an offset and a length.

new String(ch, 2, 5);
查看更多
登录 后发表回答