首页 > 试题广场 >

删除一个字符串中前面出现过的字符,只保留首次出现的字符, 例

[问答题]

删除一个字符串中前面出现过的字符,只保留首次出现的字符, 例如

"hello  it is a test and you can do it will"。

输出结果为:"helo itsandyucw"

function removeDuplicate(s) {
    let result = "";
    for (let i = 0; i < s.length; i++) {
        if (s.indexOf(s[i]) == i) {
            result = result + s[i];
        }
    } return result;
}

console.log(removeDuplicate("hello  it is a test and you can do it will"))

使用indexOf(),当且仅当字符串里的字符出现位置等于其实际位置时,将其存入结果。
这样子,之后出现的字符就被过滤掉了。
发表于 2023-03-28 08:13:47 回复(0)