我有兩個字串:
let string1 = "這里有些文字"。
let string2 = "text here as well";
我想檢查string1的結束部分是否與string2的開始部分相匹配。
我正在輸出string1 string2。在我的案例中,我不想把相同的字列印兩次。例如,我不希望列印"Some text heretext here as well"。
我如何檢查這個問題?我已經嘗試了startsWith/endsWith和一個通過從空間吐出字串的回圈。但我不認為我的方法是正確的,因為字串的匹配部分可以有不同的長度。
字串也可以包含破折號。例如,它可以是:
let string1 = "Some-text here" ;
let string2 = "text here as well";
在上面的例子中,理想的輸出將是"這里也有一些文字"。
uj5u.com熱心網友回復:
你可以使用String.substring來獲取兩個輸入值的子串,從string1的末尾和string2的開始。如果這些是相同的,我們已經找到了我們的重疊。
let string1 = "Some-text here"/span>;
let string2 = "text here as well";
let overlap = null;
for(let i = 1; i <= string1.length; i ) {
if (string1.substring(string1. length - i) === string2.substring(0, i)) {
overlap = string2.substring(0, i) 。
break。
}
}
console.log('Overlap:'/span>, overlap)。
let concatenated = string1.replace(overlap, '') string2;
console.log('string1 string2:',concatenated);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
下面是一個可能的暴力解決方法:
let resultIdx = 0;
for (let idx = 0; idx < Math. min(string1.length, string2.length); idx ) {
if (string2.substring(0, idx) === string1. substring(string1.length - idx)) {
resultIdx = idx
}
}
let result = string1 string2.substring(resultIdx)
我們在字串上回圈,并檢查是否有子串匹配。如果有,我們保存最后的索引,并使用它來建立解決方案(保存在變數result中)。這是你想要找到的嗎?
uj5u.com熱心網友回復:
。let string1 = "Some-text here" ;
let string2 = "text here as well";
let splitString1 = string1.split(" ") 。
let splitString2 = string2.split(" ") 。
let stringSet1 = new Set(splitString1)。
let stringSet2 = new Set(splitString2)。
console.log(stringSet1)。
console.log(stringSet2)。
function wordDiff(strSet1, strSet2) {
let _wordDiff = new Set(stringSet1)。
for (let elem of stringSet2) {
if (_wordDiff.has(elem)) {}。else {
_wordDiff.add(elem)。
}
}
return _wordDiff;
}
let result = wordDiff(stringSet1, stringSet2)。
console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/307878.html
標籤:
