【问题标题】:LinkedList toString method; converting to a single string? [duplicate]链表 toString 方法;转换为单个字符串? [复制]
【发布时间】:2016-06-05 01:33:10
【问题描述】:

我正在尝试将链表节点的值转换为单个字符串。例如:

"c" -> "a" -> "t"

所以当我使用内置的toString 方法时,我会得到这个作为输出。

"[c, a, t]"

整个东西都是一个字符串。有没有什么方法可以让我把它合并成一个字符串,像这样?

"cat"

【问题讨论】:

  • 重写 toString 方法并使用 replaceAll("\\W+", "") 删除所有非 [a-zA-Z0-9_] 字符。
  • @MarounMaroun,所以我在覆盖方法中运行super(),然后将replaceall 添加到覆盖方法中?

标签: java string linked-list tostring


【解决方案1】:
        LinkedList<String> list=new LinkedList<String>();
        list.add("c");
        list.add("a");
        list.add("t");
        System.out.println(list.toString().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\, ", ""));

【讨论】:

    【解决方案2】:

    如果你使用Java 8,你可以使用joining()collector:

    LinkedList<String> strings = new LinkedList<>();
    strings.add("c");
    strings.add("a");
    strings.add("t");
    
    System.out.println(strings.stream().collect(Collectors.joining()));
    

    输出:"cat"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      相关资源
      最近更新 更多