Simple way to (re-) set an string array?

Back to topics list To post a new topic, please log in or register
avatar
2017
gooly 2015.03.11 12:01
 

Is there a simpler way to reset a string array than to loop through each individual reference?

If I define that array i can write:

static string sC[] = {"","","","","","","","","",""};

If I try to 'repeat' this later in the code:

  ...
  sC[] = {"","","","","","","","","",""};

I'll get an error and the mt4 functions ArrayFill() or ArrayInitialize() work only for numerical arrays :(

Ok, I can loop:

string sC[] = {"1","2","3","4","5","6","7","8","9","0"};
int sz = ArraySize(sC) - 1; // SIC!!
while(sz>=0) sC[(sz--)]="";

But I'd prefer something like the the definition...

remark: Other than I am used to (sz--) is not decremented at first and then used as index no. but after that!

This will give you an Array out of Range Error:

string sC[] = {"1","2","3","4","5","6","7","8","9","0"};
int sz = ArraySize(sC);
while(sz>0) sC[(sz--)]="";

Well ok I just saw in the reference and checked it out that this (--sz) works:

string sC[] = {"1","2","3","4","5","6","7","8","9","0"};
int sz = ArraySize(sC);
while(sz>0) sC[(--sz)]="";


avatar
Moderator
3419
GumRai 2015.03.11 12:42 #
 

I'm not totally sure, but maybe by re-sizing the array to 0 and then re-sizing again to whatever you want all values will be "".

Otherwise you could use string split

This simple code shows how it would work. Note that if you want the array size as 10 the string will be 9 commas (10-1)

 

   string ArrayInit=",,,,,,,,,";
   string sC[];
   
   ushort u_sep=StringGetCharacter(",",0);
   StringSplit(ArrayInit,u_sep,sC);
   int as=ArraySize(sC);
   string text="Array Size="+(string)as;
   for(int x=0;x<as;x++)
      {
      if(sC[x]=="")
         text+=" "+(string)x+" is Blank,";
      else
         text+=" "+(string)x+" is NOT Blank,";
      } 
   Print(text);
   
   ArrayInit=",,,,";
   StringSplit(ArrayInit,u_sep,sC);
   as=ArraySize(sC);
   text="Array Size="+(string)as;
   for(int x=0;x<as;x++)
      {
      if(sC[x]=="")
         text+=" "+(string)x+" is Blank,";
      else
         text+=" "+(string)x+" is NOT Blank,";
      } 
   Print(text);
Back to topics list  

To add comments, please log in or register