Using StringBuilder class to input text into a program

edited October 2013 in Programming Questions

I want to make a program that accepts a string as a command, and then splits it at a period, so that if I input "move.12", the program will be able to use both word and the number as commands. In other words, is there a split() function for a stringBuilder variable? Here is my current code:

//stringBuilder for the command
StringBuilder text = new StringBuilder("");

void setup()  {
}
void draw() {
}
void keyTyped() {
  if(key == ENTER)
    {//enter the code to split the string and assign it to ints. I was thinking something like:
     String datastring[] = split(text, "."); //but you can't do this
     text.setLength(0); //clears the text string to make it ready for the next command
    }
   else
    {text.append(key); //adds each new character to text.
     println(text);
    }
}

Answers

  • _vk_vk
    edited October 2013 Answer ✓

    Without digging in it... You can use text.toString() to have a String out of a StringBuilder.

    //stringBuilder for the command
    StringBuilder text = new StringBuilder("move.12");
    
    void setup()  {
    }
    void draw() {
    }
    void keyTyped() {
      if(key == ENTER)
        {//enter the code to split the string and assign it to ints. I was thinking something like:
         String datastring[] = split(text.toString(), "."); //but you can't do this
         text.setLength(0); //clears the text string to make it ready for the next command
         println(datastring);
        }
       else
        {text.append(key); //adds each new character to text.
         println(text);
        }
    }
    

    and here StringBuilder reference...

  • Yep. it works. Thanks

  • Note that it is recommended to avoid doing stuff like: text += char; in a loop when text is a String, because it creates lot of overhead (generating a new String on each step, throwing away the previous one).

    But while StringBuilder is a good solution for this problem, it is a bit overkill for your need, when you add a new char only when the user hits a key, which is quite slow: there is no problem of garbage collection and memory filling there.

Sign In or Register to comment.