【问题标题】:How to print the text如何打印文本
【发布时间】:2016-10-12 05:58:41
【问题描述】:
public class usermain {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Map<String, String> map = new HashMap<String, String>();
    String test = "cat=\"dog\"; + abc=\"bcd\"; ";

        System.out.println(test);   


    // split on ':' and on '::'
    String[] parts = test.split("");

    for (int i = 0; i < parts.length; i += 2) {
        map.put(parts[i], parts[i + 1]);
    }

    for (String s : map.keySet()) {
        System.out.println(map);
    }

}

}

我想在数组中显示:

[cat] = dog
[abc] = bcd

【问题讨论】:

  • 只用空字符串替换分号和加号即可,无需拆分。
  • 我想在数组中打印 cat =dog 和 abc =bcd
  • 在最终的 for 循环中,给“String s”赋予更合适的名称,例如“字符串键”,让您更容易理解字符串中的这个值是什么。然后在同一个 for 循环中打印出“key”(不是 map),更进一步,您应该稍后打印“map.get(key)”(这会返回与 key 关联的值)

标签: java string


【解决方案1】:
public class usermain {

public static void main(String[] args) {

    String test = "cat=\"dog\"; + abc=\"bcd\"; ";

        System.out.println(test);   


    String[] parts = test.split(" + ");

    for (int i = 0; i < parts.length; i += 1) {
        System.out.println("[" + parts.replace (';','').replace ("=","]="));
    }


}

}

【讨论】:

    【解决方案2】:

    您可以使用适当格式的值来拆分它,然后您可以使用 entrySet() 打印键和值

    参考 https://stackoverflow.com/a/3344768/3496666

    字符串测试 = "cat=\"dog\"; + abc=\"bcd\"; ";

    对于上述字符串,先将双引号、分号、空格等除'+'以外的字符替换为空字符

    然后用 '+' 分割字符串作为字符串数组,然后用 '=' 分割字符串数组中的每个字符串。现在您可以使用 entrySet() 来按预期显示输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-08
      • 2017-06-19
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 2014-08-28
      相关资源
      最近更新 更多