ADVERTISEMENT
ADVERTISEMENT

Home » Kotlin » Kotlin programs » Kotlin string programs

Kotlin program to check whether two strings are anagram of each other

Kotlin | Check anagram strings: Here, we are going to learn how to check whether two strings are anagram of each other in Kotlin programming language?
Submitted by IncludeHelp, on April 29, 2020

What is anagram?

An anagram is a string that can be formed by rearranging the characters of a different string using all the original characters exactly once.

For example, "anagram" can be rearranged into "nag a ram", "binary" can be rearranged into "brainy".

Given two strings, we have to check whether they are anagram of each other.

Example:

    Input:
    String1 = "binary"
    String2 = "brainy"

    Output:
    True
    Both are anagram strings

Program to check whether two strings are anagram of each other in Kotlin

package com.includehelp.basic

import java.util.*


/**
 * Function to check two strings are anagram string or not
 */
fun isAnagrams(str1: String, str2: String): Boolean {
    //Both String Length must be Equal
    if (str1.length != str2.length) {
        return false
    }

    //Convert Strings to character Array
    val strArray1 = str1.toCharArray()
    val strArray2 = str2.toCharArray()

    //Sort the Arrays
    Arrays.sort(strArray1)
    Arrays.sort(strArray2)

    //Convert Arrays to String
    val sortedStr1 = String(strArray1)
    val sortedStr2 = String(strArray2)

    //Check Both String Equals or not After Sorting 
    //and Return value True or False
    return sortedStr1 == sortedStr2
}

//Main Function, entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val sc = Scanner(System.`in`)

    //Enter String Value
    println("Enter String1 : ")
    val str1: String = sc.nextLine()

    println("Enter String2 : ")
    val str2: String = sc.next()

    //Call Function to  check anagram String
    if (isAnagrams(str1, str2)) {
        println("Anagram Strings !!")
    } else {
        println("Strings are not Anagram !!")
    }
}

Output

Run 1:
Enter String1 :
raghu
Enter String2 :
gharu
Anagram Strings !!
---
Enter String1 :
Hello
Enter String2 :
includehelp
Strings are not Anagram !!
---
Enter String1 :
john
Enter String2 :
hnoj
Anagram Strings !!
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.