我需要(在JavaScript
,也许使用RegEx
?或者一些React
组件)来比较两个字符串和粗体--所有的单词/字符都不存在于“源”字符串中。
例如:
“业务计划”与“业务计划”相比,应返回“业务pla__plafond”。
与“计划和监控”相比较的“业务计划”应返回“计划和监视”。
目前,我使用了这种方法,但不幸的是,并不是所有情况下,我都找不到这样的问题:
compareStrings(a, b) {
let i = 0;
let j = 0;
let result = "";
while (j < b.length)
{
if (a[i] === ' ') {
i++;
} else {
if ((a[i] != b[j]) || (b[j] === ' ') || i == a.length)
result += b[j];
else i++;
// }
}
j++;
}
return result;
}
有人能帮我吗?
发布于 2019-09-13 14:19:06
从您的示例中,我建议采用以下字符串比较策略:
a
和b
b
,并在a
中找到它的第一次出现a
中找到仍发生b
的另一个偏移量。b
的其余字符。如果这是您想要实现的,您可以尝试对您的算法进行以下改进:
function compareStrings(a, b) {
let i = 0;
let j = 0;
let search = ''; // current search term (substring of b)
while (j < b.length) {
search += b[j]; // add another character of b to search string
if (a.indexOf(search) > -1) { // search is found in b, continue
j++;
} else {
return b.substr(j); // return remaining substring of b which is not part of a
}
}
}
console.info(compareStrings('business plan', 'business plafond')); // fond
console.info(compareStrings('business plan', 'plan and monitoring')); // and monitoring
我已经看到,在您的原始代码中,您也希望跳过空格字符;但是,我不太明白这种行为是否会导致错误的输出.如果您想忽略空白,请尝试使用a.replace(/\s/g)
(resp )。( b
)。
发布于 2019-09-13 13:54:04
https://stackoverflow.com/questions/57924886
复制相似问题