//字符替换函数 用户输入原始字符串 替换字符 替换后字符 替换个数
"use strict"
let readline = require("readline-sync");
console.log("请输入字符串");
let str = readline.question("");
console.log("请输入要替换的字符");
let before = readline.question("");
console.log("请输入替换后的字符");
let after = readline.question("");
console.log("请输入要替换的个数");
let count = readline.question("");
console.log(strReplace(str,before,after,count));
function strReplace(str,before,after,count)
{
let num = 0;
let arr = str.split("");//将字符串转为数组
//遍历数组进行,找到就替换
for(let i=0;i<arr.length;i++){
if(num == count)// 如果替换次数达到用户输入的次数break
{
break;
}
if(arr[i] == before)
{
arr[i] = after;
num ++;//num保存替换的次数
}
}
str = arr.join("");//重新将数组转为字符串
return str;
}