当前位置: 面试刷题>> 字符串替换 (经典算法题500道)


题目描述补充

题目:字符串替换

给定一个字符串 s 和一个字典 dict,其中 dict 包含多个键值对,键为待替换的子字符串,值为替换后的字符串。请编写一个函数,该函数遍历字符串 s,将所有在 dict 中作为键出现的子字符串替换为对应的值。如果某个子字符串在 dict 中有多个匹配项,则替换为最先遇到的匹配项的值。

示例输入

  • 字符串 s = "hello world, welcome to code class"
  • 字典 dict = {"world": "earth", "code": "programming"}

示例输出

  • "hello earth, welcome to programming class"

PHP 示例代码

function replaceString($s, $dict) {
    foreach ($dict as $key => $value) {
        $s = str_replace($key, $value, $s);
    }
    return $s;
}

$s = "hello world, welcome to code class";
$dict = ["world" => "earth", "code" => "programming"];
echo replaceString($s, $dict); // 输出: hello earth, welcome to programming class

// 码小课网站中有更多相关内容分享给大家学习

Python 示例代码

def replace_string(s, dict_replacement):
    for key, value in dict_replacement.items():
        s = s.replace(key, value)
    return s

s = "hello world, welcome to code class"
dict_replacement = {"world": "earth", "code": "programming"}
print(replace_string(s, dict_replacement))  # 输出: hello earth, welcome to programming class

# 码小课网站中有更多相关内容分享给大家学习

JavaScript 示例代码

function replaceString(s, dict) {
    for (let key in dict) {
        if (dict.hasOwnProperty(key)) {
            s = s.replace(new RegExp(key, 'g'), dict[key]);
        }
    }
    return s;
}

let s = "hello world, welcome to code class";
let dict = {"world": "earth", "code": "programming"};
console.log(replaceString(s, dict)); // 输出: hello earth, welcome to programming class

// 码小课网站中有更多相关内容分享给大家学习

以上代码示例均实现了题目要求的功能,并提供了简单的注释和输出示例。请注意,在 JavaScript 示例中,为了全局替换所有匹配的子字符串,使用了正则表达式并设置了全局标志 'g'

推荐面试题