有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中通过逐字符添加字符从字符数组创建字符串

如何在Java中通过逐字符添加字符来创建字符串。 我必须这样做,因为我必须在字母之间加一个“,”。 我这样试过,但没有成功

String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;

for (int i = 0; i<l; i++){
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){
    ret += a[v];
    ret += rel;
}

共 (3) 个答案

  1. # 1 楼答案

    看看这个:

    //Word to be delimited by commas    
        String t = "ThisIsATest";
    
        //get length of word. 
        int l = t.length(); //4
    
        char[] a;
        a = new char[l];
        // we will set this to a comma below inside the loop
        String rel = "";
        //set ret to empty string instead of null otherwise the word "null" gets put at the front of your return string
        String ret = "";
    
        for (int i = 0; i<l; i++){
            //you had 0 instead of 'i' as the parameter of t.charAt. You need to iterate through the elements of the string as well
            a[i] = new Character(t.charAt(i));
        }
    
        for (int v = 0; v<l; v++){
        /*set rel to empty string so that you can add it BEFORE the first element of the array and then afterwards change it to a comma
         this prevents you from having an extra comma at the end of your list.         */
    
            ret += rel;
            ret += a[v];
            rel = ",";
        } 
        System.out.println(ret);
    
  2. # 2 楼答案

    String text = "mydata";
    char[] arrayText = text.toCharArray();
    char[] arrayNew = new char[arrayText.length*2];
    for(int i = 0, j = 0; i < arrayText.length; i++, j+=2){
        arrayNew[j] = arrayText[i];
        arrayNew[j+1] = ',';
    }
    String stringArray = new String(arrayNew);
    System.out.println(stringArray);
    

    结果

    m,y,d,a,t,a,
    
  3. # 3 楼答案

    我已经把你代码中的错误放在了注释中

    String t;
    int l = t.length();
    char[] a;
    a = new char[l];
    String rel = ",";
    String ret = null; //you initialize ret to null, it should be "";
    
    for (int i = 0; i<l; i++){
        //you always set it to the character at position 0, you should do t.charAt(i)
        //you don't need to use the wrapper class just t.charAt(i) will be fine.
        a[i] = new Character(t.charAt(0)); 
    }
    
    for (int v = 0; v<l; v--){//you decrement v instead of incrementing it, this will lead to exceptions
        ret += a[v];
        ret += rel;//you always add the delimiter, note that this will lead to a trailing delimiter at the end
    }
    

    你可能想试试StringBuilder。它比使用字符串串联要高效得多。使用数组a也不是真正必要的。看看这个实现

    String t = "Test";
    StringBuilder builder = new StringBuilder();
    if(t.length() > 0){
        builder.append(t.charAt(0));
        for(int i=1;i<t.length();i++){
            builder.append(",");
            builder.append(t.charAt(i));
        }
    }
    System.out.println(builder.toString());