Monday, February 24, 2020

android kotlin - How to match two strings region

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)

        val string1 = "This is a sample string to test the function."

        val string2 = "This is another SAMPLE string to test the " +
                "string region matches method."

        textView.text = string1
        textView.append("\n\n")
        textView.append(string2)

        /*
            documentation source kotlinlang.org
                Returns true if the specified range in this char sequence
                is equal to the specified range in another char sequence.
        */

        val result = string1.regionMatches(
                9, // thisOffset: Int
                 string2, //other: CharSequence
                15, // otherOffset: Int,
                13, // length: Int,
                true // ignoreCase: Boolean = false
            )

        textView.append("\n\n\n")
        textView.append("String1 and string2 region" +
                " (sample string) matches? $result")

    }
}
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="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#2A52BE"
        android:textStyle="normal"
        android:textSize="27sp"
        android:fontFamily="sans-serif-condensed"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
More android examples