Abhishek
Abhishek

Reputation: 59

How to remove a char from char array with index in Kotlin

I'm starting out with Kotlin. I want to remove a specific charter of a charArray using indices. For example if there's an array ar = (a,b,c,d,e,f,g,h), how do I remove ar[x] from it...?

Upvotes: 1

Views: 2249

Answers (1)

codegames
codegames

Reputation: 1921

as @Tenfour04 mentioned you can't remove element from an array. because it has fixed size. but you can make a new array without that element.

if array be [ a, b, c, d] for removing index 1 you can do this:

array = array.filterIndexed { i, _ -> i !== 1 }

now array is [ a, c, d ].

result of filterIndexed is a new list. if you explicitly want an array you have to convert the result like this:

array = array.filterIndexed { i, _ -> i !== 1 }.toCharArray()

or

array = array.filterIndexed { i, _ -> i !== 1 }.toTypedArray()

Upvotes: 4

Related Questions