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 字符串