我想找到不同的字符在一个字符串中,而不是在另一个字符串中。假设firstString包含ABC,而secondString现在包含BC,那么输出op1应该包含‘firstString中明显存在但在secondString中不存在的字符’,即A和op2应该包含“secondString中明显存在但在firstString中不包含的字符”,即在本例中为null。如果firstString是'SBG‘而secondString是’secondString‘op1应该是'S’op2应该是'ANLORE‘
发布于 2022-04-22 20:17:29
我建议使用Javascripts 设置并过滤掉不存在的元素:
// returns the distinct characters found in string1
// but not in string2 as an array
function findDistinctChars(string1, string2) {
const set1 = new Set(string1)
const set2 = new Set(string2)
return [...set1].filter(char => !set2.has(char))
}
// example usage
const s1 = "aaabcde"
const s2 = "efghi"
// run for string one and then two
const op1 = findDistinctChars(s1, s2)
const op2 = findDistinctChars(s2, s1)
// output results
console.log(op1)
console.log(op2)
https://stackoverflow.com/questions/71973840
复制相似问题