Hello I have a programme that loads a piece of text from a file. In this case it loads "drawrect(4,10,20,20);" from the txt file and stores it in a string. I then use substrings to change the string into just "4,10,20,20" which is good but I need to simplify it down even more to four strings each with one of those 4 numbers in it.

Currently I use:

void drawRectMethod(String s){
  String var1,var2,var3,var4;
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));

to simplify the string down to "4,10,20,20" but this wont work to store each number in a separate string. How can I can I store each variable in a separate string. The numbers will be stored in var1 - var4.

  • This is not nearly related to Arduino at all?
    – Paul
    Feb 17 '16 at 20:05
  • ye it is an Arduino based project the string is loaded from an sd card that is attached to an arduino Feb 17 '16 at 20:05
  • Ah, okay, an Arduino is sending text over USB. But what is receiving it at the moment?
    – Paul
    Feb 17 '16 at 20:07
  • the sd card sends text to a string on the Arduino the Arduino then reads it and if it says drawrect(4,10,20,20) it will draw a rectangle on my nokia 5110 screen. I just cant figure out how to store each of the 4 numbers in a separate string hopefully using the substring method like I have been doing before Feb 17 '16 at 20:09
  • 1
    Why is the title: "Java loading from file"?
    – Paul
    Feb 17 '16 at 20:13

Need some more help? As I previously wrote that snippet I might as well continue until you understand how to use indexOf() and substring().

  String s = "draw(10,20,30,40)";

  // Parse the argument list
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));

  // Parse comma separated arguments
  String arg[4];
  for (int i = 0; i < 3; i++) {
    int ix = s.indexOf(',');
    arg[i] = s.substring(0, ix);
    s = s.substring(ix + 1);
  arg[3] = s;

There is absolutely no error handling in this. You will have to add that. You can also improve the parse of the right parenthesis. That could be added last instead.

Later in the game we will come to why using String is a bad idea and why a character buffer and the standard library functions such as strtok() is a much better solution strategy both performance and memory footprint and especially heap.

  char* s = (char*) "draw(10,20,30,40)";
  s = strtok(s, "(),");
  while ((s = strtok(NULL, "(),")) != NULL)

Maybe the simplest solution is to use sscanf(). That will also do the conversion from text to binary.

  const char* s = "draw(10,20,30,40)";
  int x, y, w, h;
  int n = sscanf(s, "draw(%d,%d,%d,%d)", &x, &y, &w, &h);


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.