C # Trim spaces inside an array (remove 0)

If I have the following array:

int[] arr = { 123, 243, 0, 0, 123, 0, 0, 0, 123 }; 

How can I move all values ​​that are not equal to 0, since they can build an array like this as follows:

 int[] arr = { 123, 243, 123, 123, 0, 0, 0, 0, 0 }; 

Thanks!

+4
source share
7 answers

OrderBy:

 int[] arr = { 123, 243, 0, 0, 123, 0, 0, 0, 123 }.OrderBy(x => x == 0).ToArray(); 
+4
source

As with LINQ:

 var result = arr.Where(x => x != 0).Concat(arr.Where(x => x == 0)).ToArray(); 

It is quite readable and has linear time complexity. On the other hand, it works out of place and requires two passes above the entrance.

+11
source

All answers still create a new array. In fact, you can just move objects in one cycle and then fill in the remaining 0s.

 public static void ShiftZerosRight(this int[] arr) { int j = 0; while (j < arr.Length && arr[j] != 0) { j++; } for (int i = j; i < arr.Length; i++) { if (arr[i] != 0) { arr[j++] = arr[i]; } } while (j < arr.Length) { arr[j++] = 0; } } 

Not as elegant as single-line LINQ expressions, but more efficient - it does not create any new objects (and LINQ creates several and the last new array), and this is one pass through the array. As an extension method, complexity is not observed in the main building, where it can be used as:

 int arr[] = { ... }; arr.ShiftZerosRight(); 
+3
source

Perhaps using Linq with:

  int[] arr = { 123, 243, 0, 0, 123, 0, 0, 0, 123 }; arr = arr.OrderByDescending(a => a > 0).ToArray<int>(); 
+2
source

Try the following:

 arr.OrderBy(x=>x == 0).ToArray(); 
+1
source

Create a new array and pass values ​​to it.

 int[] newArr = new int[arr.Length]; int i = 0; foreach ( var v in arr ) { if (v != 0) { newArr[i++] = v; } } arr = newArr; 

Since int is a value type, the array is initialized with all zeros. Then we copy the values ​​one at a time, only increasing the destination index i if the value is not 0. More detailed than the Linq examples given, and obviously uncooled. But if you are a student, it will be easier for you to follow.

0
source

This piece of code does not create another array. Here "x []" is your array. You take the value of the 1st 0 and replace it with a nonzero number.

 int i=0,j=0,index=0,temp=0; for(i=0;i<x.length;i++) { if(x[i]==0) { index=i; for(j=index;j<x.length;j++) { if(x[j]!=0) { temp=x[j]; x[j]=x[i]; x[i]=temp; break; } } } } 
0
source

Source: https://habr.com/ru/post/1395249/


All Articles