如何从char数组的已知元素创建String

时间:2014-02-27 12:26:09

标签: java arrays string char string-concatenation

我有一个来自字符串的char数组:

public class CharIndexes {
    public static void main (String[] args) {
        String a = "A good example is the best sermon.";
        int len = a.length();
        char[] tempA = new char[len] ;
        for (int i = 0; i < len; i++) {
             tempA[i] = a.charAt(i);
        }
}

我需要创建2个字符串:来自元素a1的{​​{1}}和来自[3],[0],[28]的{​​{1}},并获得等于a2的字符串(即3 ,0,28个元素+ 15,24):

[15],[24]

我该怎么办?

5 个答案:

答案 0 :(得分:1)

也许是这样的......?

String a = "A good example is the best sermon.";
char[] c = a.toCharArray();

String a1 = new String(new char[]{c[3],c[0],c[28]});
String a2 = new String(new char[]{c[15],c[24]});

System.out.println(a1+a2);

答案 1 :(得分:1)

String a = new StringBuffer().append(a.charAt(...)).append(...).toString();
String b = new StringBuffer().append(a.charAt(...)).append(...).toString();
System.out(a.concat(b));

答案 2 :(得分:1)

您可以像这样创建一个字符数组

char [] a1 = new char[] {tempA[3], tempA[0], tempA[28]};
char [] a2 = new char[] {tempA[15], temp[24]};

然后你可以像这个

那样简单地构建你的目标字符串
System.out.println(new String(a1) + new String(a2));

答案 3 :(得分:0)

以下是绿洲如何形成:

String string = "A good example is the best sermon.";
char[] chars = string.toCharArray();

String firstPart = new String(new char[] { chars[3], chars[0], chars[28] });
String secondPart = new String(new char[] { chars[15], chars[24] });

String oasis = firstPart.concat(secondPart);

或者,

String string = "A good example is the best sermon.";
char[] chars = string.toCharArray();

StringBuilder firstPart = new StringBuilder().append(chars[3]).append(chars[0]).append(chars[28]);
StringBuilder secondPart = new StringBuilder().append(chars[15]).append(chars[24]);

String oasis = firstPart.append(secondPart).toString();

答案 4 :(得分:0)

public class CharIndexes 
{
    public static void main (String[] args) 
    {
        String a = "A good example is the best sermon.";
        int len = a.length();
        char[] tempA = new char[len] ;
        for (int i = 0; i < len; i++) 
        {
             tempA[i] = a.charAt(i);
        }
        String a1 = new String (tempA[3]+""+tempA[9]+""+tempA[27]);
        String a2 = new String (tempA[15]+""+tempA[24]);
        System.out.print(a1+a2);
    }
}