[英]Concatenate two (or more) strings and result in the same string regardless of order
I want to concatenate some strings into single string.我想将一些字符串连接成单个字符串。 (ex: "Pen" and "Apple" -> "PenApple") But, I want the outputting string to be the same regardless of the order they're concatenated in. (例如:“Pen”和“Apple”->“PenApple”)但是,无论它们连接的顺序如何,我都希望输出字符串相同。
Each string contain non-Unicode characters.每个字符串都包含非 Unicode 字符。
If the implementation of newConcat("Pen", "Apple")
outputs "PenApple"
then newConcat("Pen", "Apple") === newConcat("", "PenApple")
如果newConcat("Pen", "Apple")
的实现输出"PenApple"
那么newConcat("Pen", "Apple") === newConcat("", "PenApple")
and likewise, newConcat("Pen", "Apple") === newConcat("", "ApplePen")
then newConcat("Pen", "Apple")
must output "ApplePen"
同样, newConcat("Pen", "Apple") === newConcat("", "ApplePen")
然后newConcat("Pen", "Apple")
必须 output "ApplePen"
In general, these test cases needs to be true as well:通常,这些测试用例也需要为真:
newConcat("Pen", "Apple") === newConcat("Apple", "Pen"); // true
newConcat("Pen", "Apple") === newConcat("_P3n", "_App13"); // false
newConcat("Pen", "Pineapple", "Apple", "Pen") === newConcat("Apple", "Pen", "Pen", "Pineapple"); // true
What I've come up with so far, is to put the strings in an array, sort it, then return it joined as string.到目前为止,我想出的是将字符串放入一个数组中,对其进行排序,然后将其作为字符串返回。
function newConcat( ...strings ) {
const newArray = []
newArray.push(...strings)
return newArray.sort().join("")
}
I want to know if there's a better way to do this than to sort the strings inside an array.我想知道是否有比对数组中的字符串进行排序更好的方法来做到这一点。 What if I want to control what order they should be put together.如果我想控制它们应该放在一起的顺序怎么办。
I would pass the results as an array and order it before returning like this.我会将结果作为数组传递并在像这样返回之前对其进行排序。
I hope this helps!我希望这有帮助!
function newConcat(array) { array.sort(); var concat = ""; for (var i=0; i<array.length;i++){ concat = concat +array[i] } return concat } console.log(newConcat(["Pen","Apple"])); console.log(newConcat(["Pen","Apple"])===newConcat(["Pen","Apple"])); console.log(newConcat(["Pen","Apple"])===newConcat(["_P3n","_App13"])); console.log(newConcat(["Pen", "Pineapple", "Apple", "Pen"])===newConcat(["Apple", "Pen", "Pen", "Pineapple"]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.