Trimming a String Arrary

1:39 AM

Let's Say i have following array:

string[] myArray = new string[6];
            myArray[0] = "a";
            myArray[1] = "b";
            myArray[2] = " ";  //space
            myArray[3] = "c";
            myArray[4] = ""; //null
            myArray[5] = "d";
   


I want to remove the space and null parts from the array.
so after trimming the array should be like this:

            myArray[0] = "a";
            myArray[1] = "b";
            myArray[2] = "c";
            myArray[3] = "d";



Code:

public string[] TrimStringArray(string[] strArray)
        {
            
            int c = 0;
            foreach (string str in strArray)
            {
                if (str != "" && str != null)
                {
                    c++;
                }
            }

            string[] tempArrary = new string[c];
            int j=0;
            for (int i = 0; i < strArray.Length; i++)
            {
                if( strArray[i] != null && strArray[i] != "")
                {
                    tempArrary[j] = strArray[i];
                    j++;
                }
            }

            return tempArrary;
        }
   

Examle:
myArray = TrimStringArray(myArray);

0 comments:

Post a Comment