kotlin 字符串_Kotlin程序,用于检查两个字符串是否彼此字谜

kotlin 字符串

什么是字谜? (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".

例如,“ anagram”可以重新排列为“ nag ram”,“ binary”可以重新排列为“ 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

在Kotlin中检查两个字符串是否彼此变位的程序 (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 !!


翻译自: https://www.includehelp.com/kotlin/check-whether-two-strings-are-anagram-of-each-other.aspx

kotlin 字符串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值