【问题标题】:How to save string in one line? [duplicate]如何将字符串保存在一行中? [复制]
【发布时间】:2013-06-11 17:40:59
【问题描述】:

我有几个字符串:a,b,c,d,e。我想将它们作为单个字符串保存到文件 FILENAME a b c d:e。问题 - 我需要保留 d;e 在新行开始的信息。

String str = a
        + " "
        + b

        + c
        + "\n "
        + d
        + ";"
        + e + "\r\n";
try {
    fos = openFileOutput(FILENAME, Context.MODE_APPEND);
    fos.write(str.getBytes());
    fos.flush();
    fos.close();
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

【问题讨论】:

标签: java android string io


【解决方案1】:

你可以使用String.format()(如果你熟悉C/C++,这个类似于printf())。例如,以下为您提供所需的字符串格式:

String.format("%s %s %s%n%s;%s%n", a, b, c, d, e);

其中 %n 是换行符。

如果你输出的字符串很长,那么你也可以使用StringBuilderString.format()

【讨论】:

  • 现在我已经以这种方式完成了,但它仍然保存为文件中的 2 行,而我需要一个。
【解决方案2】:

现在我大概明白你的问题了。你的问题是一个格式为"%s %s %s\n%s:%s\n"的输入字符串,我如何将它们以"%s %s %s %s:%s"的格式存储在一个文件中,我想你知道如何做第二部分。

在第一部分,您需要解析输入字符串以允许您获取五个元素。一种简单的方法是使用String.split() 函数,它返回一个字符串数组,给定输入字符串和描述为正则表达式的分隔符:

String[]    String.split(String regex)
// Splits this string around matches of the given regular expression.

例如,你的情况是:

String[] elements = str.split("[ ;\n\r]");

Here 是关于正则表达式的更多信息。

如果您并不真正关心输入字符串中的元素,而只是简单地删除换行符,那么您可以使用String.replaceAll()

在你的情况下,它会是:

String newStr = str.replaceAll("[\n\r]", "");

同样,它的第一个输入参数是一个正则表达式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 2022-07-15
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2015-10-05
    相关资源
    最近更新 更多