1

I am kind of new with C# and I was wondering if there is a function to remove specific values (0) at the end of an array of float?

For example:

float[] samples = {0.0, 4.0, 2.5, ..., 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

after the call I want my samples to be:

samples == {0.0, 4.0, 2.5, ..., 2.0}

Thank you for your help

dymanoid
  • 14,771
  • 4
  • 36
  • 64
FSebH
  • 33
  • 5

3 Answers3

6

I'd start by finding the final non-zero index:

int i = samples.Length - 1;
for( ; i >= 0; i--)
    if(samples[i] != 0.0F) break;

then I'd either copy that subset (0-i inclusive), or to avoid allocations I'd use a Span<T> to limit myself to that part without creating a new array:

var span = new Span<float>(samples, 0, i + 1);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2
float[] samples = { 0.0f, 4.0f, 2.5f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };

var clean = new List<float>();
for (int i = 0; i <samples.Length; i++)
{
    if (i == 0)
    {
        if (samples[i] == 0.0f) clean.Add(samples[i]);
        continue;
    }
    if (samples[i] != 0.0f) clean.Add(samples[i]);
}

//clean.ToArray() = float[]

This may be better solution

float[] samples = { 0.0f, 4.0f, 2.5f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };

List<float> clean = samples.ToList();
for(int i=clean.Count-1; i>0; i--)
{
    if (clean[i] == 0.0f) clean.RemoveAt(i);
    else break;
}

//clean.ToArray()
0

For now, I've tried this, it works for what I want but I'm not sure it is the simplest:

                float[] samples = new float[AudioFeedbackList[i].GetComponent<AudioSource>().clip.samples * AudioFeedbackList[i].GetComponent<AudioSource>().clip.channels];

            List<float> sampi = new List<float>();
            sampi.AddRange(samples);
            int j = sampi.Count;

            while (sampi[j - 1] == 0.0f)
            {
                j--;
            }

            List<float> newSampi = new List<float>();
            for (int k = 0; k < j; k++)
            {
                newSampi.Add(sampi[k]);
            }


            samples = newSampi.ToArray();

Thank you for the feedback!

FSebH
  • 33
  • 5