【问题标题】:copy only portion of char[] into String仅将 char[] 的一部分复制到 String
【发布时间】:2013-05-04 07:19:18
【问题描述】:

我有一个数组 char[] ch。我的问题如下。如何将 ch[2] 到 ch[7] 的值合并为字符串?我想在不遍历 char 数组的情况下实现这一点。有什么建议吗?

感谢您花时间回答我的问题。

【问题讨论】:

  • “将值从 ch[2] 合并到 ch[7]”是什么意思?创建一个新字符串?将这些字符插入一个新字符串?覆盖字符串中的字符?

标签: java string char


【解决方案1】:

试试这个:

        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);

输出:

左右

【讨论】:

    【解决方案2】:

    您可以为String 使用其他构造函数之一

    有一个接受一个 char 数组、一个偏移量和一个长度。

    new String(ch, 2, 5);
    

    【讨论】:

      【解决方案3】:

      使用new String(value, offset, count)reference

      其中 offset 是起始索引,count 是您的索引差异。在你的情况下,它是 7-2=5。

      显然,value 是你的字符数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-03
        • 2012-01-06
        • 2022-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多