【问题标题】:Split a sentence into two words and store as key, value in HashMap将一个句子拆分为两个单词,并作为键、值存储在 HashMap 中
【发布时间】:2015-02-17 07:25:12
【问题描述】:

我需要将一个句子分成两个字符串,第一个字符串存储为键,第二个字符串存储为 HashMap 中的值。 例如:

String sent="4562=This is example";

这是我的句子,我使用以下行拆分成两个字符串:

sent.split("=");

我想将第一个字符串 (4562) 作为键存储,第二个字符串作为值存储在 HashMap 中。

您能分享您的想法或解决问题的方法吗?

【问题讨论】:

  • 你试过 hashmap.put(key,value) 了吗?

标签: java hashmap string-split


【解决方案1】:

你在陈述你自己的答案:

HashMap<String, String> map = new HashMap<String, String>(); //initialize the hashmap
String s = "4562=This is example"; //initialize your string
String[] parts = s.split("="); //split it on the =
map.put(parts[0], parts[1]); //put it in the map as key, value

【讨论】:

    【解决方案2】:

    您可以像这样存储在哈希图中:

    String sent = "4562=This is example";
    String[] split = sent.split("=");
    HashMap<Integer, String> keysValues = new HashMap<Integer, String>();
    keysValues.put(Integer.parseInt(split[0]), split[1]);
    

    您可以将整数存储为键,将字符串存储为值...或字符串,无论哪种方式的字符串都可以根据您的需要来工作。

    【讨论】:

      【解决方案3】:

      方法split返回一个字符串数组,所以将结果存入一个字符串数组并调用hashmap.put(key,value)方法

      喜欢这个

      String[] a = split.("=");
      hasmap.put(a[0],a[1]);
      

      请注意,如果字符串中有多个 =,您将在 hashmap 的值中丢失一些 =!

      【讨论】:

        【解决方案4】:
        public static void main(String[] args) {
                Map<String, String> myMap = new HashMap<String, String>();
                String s = "4562=This is example";
                String[] parts = s.split("=");
                if (parts.length == 2) {
                    myMap.put(parts[0], parts[1]);
                }
        
                System.out.println(myMap);
            }
        

        输出

        {4562=这是示例}

        enter code here
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-22
          • 2012-10-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多