0

I have a string in arduino

String name="apple orange banana";

Is it possible to store each item in an array arr

so that

arr[0]="apple" 
arr[1]="orange" ......etc

if not store them in individual variables?

1

3 Answers 3

2

I had the same problem but found a very straight forward solution using builtin string functions:

String name="apple orange banana";

Serial.println(name);
int x;
int index = 0;
String arr[3];
int i;
for (i=0;i<3;i++){
   index = name.indexOf(' ');
   arr[i] = name.substring(0, index);
   name = name.substring(index+1);
   Serial.println(arr[i]);  
}

After running this code you get this output:

apple orange banana
apple
orange
banana

I hope it helps

Sign up to request clarification or add additional context in comments.

Comments

0

How to split a string using a specific delimiter in Arduino? I believe this would help you, you could do a while loop like:

int x;
String words[3];
while(getValue(name, ' ', x) != NULL){
     words[x] = getValue(name, ' ', x);
}

Using this function:

// https://stackoverflow.com/questions/9072320/split-string-into-string-array
String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

1 Comment

That's pretty elegant, but it fails if there's not exactly one space between "words". It'd be nice if it could be any amount of white space (including tabs).
-1

If you know your list length and the max characters per list item, you could do

char arr[3][6] = {"apple", "orange", banana"};

edit: if you are looking for something like String arr[3] you aren't going to get it because of how memory is managed with the C language

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.