【问题标题】:How do I add a character to the beginning and end of a String? [duplicate]如何在字符串的开头和结尾添加字符? [复制]
【发布时间】:2018-11-05 11:07:27
【问题描述】:
while ((output = br.readLine()) != null) {
    System.out.println(output);
}

嗨,我有这个 while 循环。此输出变量是一个字符串变量,它保留来自br.readLine()) 的输出。

假设br.readLine()) 给出了 2 行。

所以System.out.println(output); 将这些行打印为:

AAA
BBB
CCC
DDD

谁能告诉我如何在第一行的开头和最后一行的结尾添加{?像这样:

{AAA
BBB
CCC
DDD}

我尝试过这样做:

while ((output = br.readLine()) != null) {
    System.out.println("{"+output+"}");
}

这在每行之后添加了一个括号。

请帮帮我。

【问题讨论】:

标签: java loops while-loop


【解决方案1】:

我看到的最简单的解决方案是在循环之前打印开始字符,在循环之后打印结束字符。喜欢,

System.out.print("{");
while ((output = br.readLine()) != null) {
    System.out.println(output);
}
System.out.println("}");

【讨论】:

  • 没有。不能这样做,因为我想将所有内容都存储在输出变量中。
  • @Manu 和 MadProgrammer 建议您在 15 分钟前使用 StringBuilder/Joiner。这正是您所需要的。
  • @Manu 或者写信给不同的PrintStream(你可以换一个ByteArrayOutputStream)。
【解决方案2】:

请尝试以下方法:

String line = "";
while ((line = br.readLine()) != null) {
  output += line;
}

output = "{" + output + "}";

更新:

StringBuilder output = new StringBuilder("{");
String line = "";
while ((line = br.readLine()) != null) {
  output.append(line);
}
output.append("}");

【讨论】:

  • 输出 = "{" + 输出 + "}";这是空的
  • 请检查更新版本...
  • 这行得通!谢谢你:)
【解决方案3】:
public static String readData(BufferedReader br) throws IOException {
    StringBuilder buf = new StringBuilder();
    buf.append('{');

    String output;

    while ((output = br.readLine()) != null) {
        if (buf.length() > 1)
            buf.append('\n');
        buf.append(output);
    }

    return buf.append('}').toString();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多