如何通过添加char逐char在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;
}发布于 2017-06-03 16:04:23
我已经将您代码中的错误放在注释中。
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());https://stackoverflow.com/questions/44345742
复制相似问题