首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何通过在java中添加char by char从char数组创建字符串

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

Stack Overflow用户
提问于 2017-06-03 15:45:11
回答 5查看 4.1K关注 0票数 1

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

代码语言:javascript
运行
复制
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;
}
EN

Stack Overflow用户

发布于 2017-06-03 16:04:23

我已经将您代码中的错误放在注释中。

代码语言:javascript
运行
复制
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也不是真正必要的。请看一下这个实现。

代码语言:javascript
运行
复制
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());
票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44345742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档