Friday, February 21, 2020

android kotlin - String Drop DropLast DropWhile DropLastWhile example

MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // drop example
        val string = "This is a sample string."
        // Returns a string with the first n characters removed.
        val result = string.drop(5)
        textView.text = string
        textView.append("\nAfter dropping 5 chars")
        textView.append("\n$result")


        // drop last example
        val string2 = "This is another sample string."
        // Returns a string with the last n characters removed.
        val result2 = string2.dropLast(6)
        textView.append("\n\n" + string2)
        textView.append("\nAfter dropping last 6 chars")
        textView.append("\n$result2")


        // drop while example
        val string3 = "This is a example string."
        val result3 = string3.dropWhile{
            it == 'T'
        }
        textView.append("\n\n" + string3)
        textView.append("\nDrop while first char is 'T'")
        textView.append("\n$result3")


        // drop last while example
        val string4 = "This is a example text."
        val result4 = string4.dropLastWhile{
            it == '.'
        }
        textView.append("\n\n" + string4)
        textView.append("\nDrop last while last char is '.'")
        textView.append("\n$result4")
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="TextView"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textStyle="bold"
        android:textColor="#0018A8"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
More android examples