Clear whitespace of an array

Asked

Viewed 394 times

3

I’m not finding the answer p this question, simply what I want to know how to do is to remove empty positions from an array, for example:

var(0) = "Remover"
var(1) = ""
var(2) = "espaços"
var(3) = ""
var(4) = "em"
var(5) = ""
var(6) = "branco"

I want to remove the empty positions, which in this case would be var(1), var(3) and var(5),

Someone would know how to do that?

I was thinking about passing only non-empty fields to another array, but how could I do that?

I tried to do the following thing:

 Dim teste() As String
 Dim i1 As Integer = 1
 Dim i2 As Integer = 0
 Dim testesemespaco(500) As String

 teste = html.Split()

 While i1 < teste.Length

   If teste(i1) <> "" Then

        testesemespaco(i2) = teste(i1)

        i2 = i2 + 1

   End If

   i1 = i1 + 1

 End While
  • Cannot remove positions from a array, they have fixed size.

  • Not even if you try to pass only positions that are not empty to another array?

  • Then yes, but that would need to be explicit in the XD question

  • I’ll edit, kkkk

  • Would you know how to do that? I’m trying but you’re not going

  • I do. I’ll give you an answer

  • It is a string array?

  • yes, I will edit the question by putting my code that is not working

  • Let me know if it works or not.

  • Error appeared, http://prntscr.com/feb7gl

  • Missing one .ToArray() after Where. See my issue

  • Now it’s gone, thanks a brother !!!

Show 7 more comments

1 answer

1


You can do this easily with LINQ, see the example.

It will also be possible to do with a for passing through all the elements and creating another array or a list. In this case, it would be much better to create a list, because they have dynamic allocation, so it won’t be necessary to do two loops to leave only valid elements in the collection.

Dim array = New String() {"Remover", "", "espaços", "", "em", "", "branco"}
Dim novoArray = array.Where(Function(palavra) Not String.IsNullOrEmpty(palavra)).ToArray()

For Each p As String In novoArray
    Console.WriteLine(p)
Next

The expression in Where says the following:

"For each palavra, being palavra an element of array return only the one that is not null or empty".

See working on . NET Fiddle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.