How can I organize strings by their content?

edited December 2014 in Programming Questions

Hello, I have a .txt file with strings. And, you see that there are words that start and end with [ and ] respectively. My question is, how can I organize strings by these words. Imagine, the first word is [duck], how can I make that all strings from that and the next [] word are related in a Hashmap?

Thanks!

Answers

  • Hello ! What did you try ?

  • String str = "[duck]";
    str = str.replace("[", "").replace("]", "");
    println(str);
    exit();
    
  • No, but what I want is to take what is after the [duck] and include put it in a HashMap.

    Thanks for your fast answer

  • After reading the question three times, I am still unsure of what you want to do. I suggest to show a sample of text, and what is the expected result from that.

  • yes

    I have a .txt file with strings.

    please show the first ten lines. Does it look like

    • [duck] swims

    • [duck] is black

    ?

    how can I make that all strings from that and the next [] word are related in a Hashmap?

    do you mean all [duck] together, so there are multiple lines with the word duck? Or Do you mean every word in [] ?

    are related in a Hashmap?

    are related? Do you mean put them in a HashMap next to each other? hm. you could put together a class entity and one is duck? And the other is frog? And they all have fields like size, movement, color?

    ;-)

  • edited December 2014
    import java.util.Map;
    
    String stuff = "[Foo] a b c d e [Bar] f g h [Baz] i j k l";
    HashMap<String, String> stuffMap;
    
    void setup() {
      size(100, 100);
    
      stuffMap = new HashMap<String, String>();
    
      String[] explodeLeft = split(stuff, '[');
      for (int i = 1; i < explodeLeft.length; i++) {
        String[] explodeRight = split(explodeLeft[i], ']');
        stuffMap.put(explodeRight[0], trim(explodeRight[1]));
      }
    
      for (Map.Entry me : stuffMap.entrySet()) {
        print(me.getKey() + " is ");
        println(me.getValue());
      }
    
      exit();
    }
    
Sign In or Register to comment.