I have a project and i need to convert string (contain numbers and letters) to array
String name = "s111, s222, bbbb,cccc ";
and i want
array[0] = s111;
array[1] = s222;
array[2] = bbbb;
array[3] = cccc;
here is the code :
String name = "s111, s222, bbbb,cccc ";
int array[50];
int r=0,t=0;
for(int i=0;i<name.length();i++){
if(name.charAt(i) == ','){
array[t] = name.substring(r,i);
r = (i+1);
t++;
}
for(int k=0 ;k<=t ;k++){
Serial.println(array[k]);
}
When I compile I get just zeros like :
array[0] = 0;
array[1] = 0;
array[2] = 0;
array[3] = 0;
1 Answer 1
When you declare int array[50];
you declare an array of numbers so only numbers can be stored inside it. If you really want an array of strings then declare an array of strings like String array[50];
There was also a a problem that sometime you split the name
by comma, sometime by space, and sometime by comma+space. Also your code was missing closing bracket.
The algorithm has to split both by comma and my space and then take only values that have length more than one to avoid inserting empty strings.
String name = "s111, s222, bbbb,cccc ";
String array[50];
int r=0,t=0;
for(int i=0;i<name.length();i++)
{
if(name[i] == ' ' || name[i] == ',')
{
if (i-r > 1)
{
array[t] = name.substring(r,i);
t++;
}
r = (i+1);
}
}
for(int k=0 ;k<=t ;k++)
{
Serial.println(array[k]);
}
it wont work
, it uselessarray[0] = s111;
": this doesn't make sense.array
is an array ofint
s, and "s111" is not anint
.