1

假设我有两个字符串要使用分隔符“加入”。

字符串 s1 = "aaa", s2 = "bbb"; // 输入字符串
字符串 s3 = s1 + "-" + s2;// 用破折号连接字符串

我可以s3.split("-")用来获取s1s2。现在,如果s1s2包含破折号怎么办?还假设它s1可能s2包含任何可打印的 ASCII,并且我不想使用不可打印的字符作为分隔符。

在这种情况下,你会建议什么样的转义?

4

4 回答 4

4

如果我可以定义格式、分隔符等。我会使用OpenCSV并使用它的默认值。

于 2012-11-30T10:58:01.783 回答
1

这是另一个可行的解决方案,它不使用分隔符,但它连接了内爆字符串末尾的字符串长度,以便能够在之后重新分解它:

public static void main(String[] args) throws Exception {
    String imploded = implode("me", "and", "mrs.", "jones");
    System.out.println(imploded);
    String[] exploded = explode(imploded);
    System.out.println(Arrays.asList(exploded));
}

public static String implode(String... strings) {
    StringBuilder concat = new StringBuilder();
    StringBuilder lengths = new StringBuilder();
    int i = 0;
    for (String string : strings) {
        concat.append(string);
        if (i > 0) {
            lengths.append("|");
        }
        lengths.append(string.length());
        i++;
    }
    return concat.toString() + "#" + lengths.toString();
}

public static String[] explode(String string) {
    int last = string.lastIndexOf("#");
    String toExplode = string.substring(0, last);
    String[] lengths = string.substring(last + 1).split("\\|");
    String[] strings = new String[lengths.length];
    int i = 0;
    for (String length : lengths) {
        int l = Integer.valueOf(length);
        strings[i] = toExplode.substring(0, l);
        toExplode = toExplode.substring(l);
        i++;
    }
    return strings;
}

印刷:

meandmrs.jones#2|3|4|5
[me, and, mrs., jones]
于 2012-11-30T11:12:18.863 回答
1

您可以使用不常见的字符序列,例如;:;分隔符而不是单个字符。

于 2012-11-30T11:00:25.310 回答
0

为什么不将这些字符串存储在一个数组中,并在每次要将它们显示给用户时用破折号连接它们?

于 2012-11-30T10:58:44.450 回答