Character replacement functions

Alternatively the number of characters after the character replacement functions // user input original string substitution character
"use strict"
let readline = require("readline-sync");
the console.log ( "Please enter the string");
let str = readline.question("");
console.log ( "Please enter the characters to be replaced");
let before = readline.question("");
console.log ( "Please enter the replacement character");
let after = readline.question("");
the console.log ( "Please enter the number to replace");
let count = readline.question("");
console.log(strReplace(str,before,after,count));
function strReplace(str,before,after,count)
{
let num = 0;
let arr = str.split ( ""); // string to the array
// traverse the array, to find replacement
for(let i=0;i<arr.length;i++){
if (num == count) // If you replace the number entered by the user to achieve the number of break
{
break;
}
if(arr[i] == before)
{
arr[i] = after;
num ++; // num times saving replaced
}
}
str = arr.join ( ""); // re-array into a string
return str;
}



Guess you like

Origin www.cnblogs.com/dbda/p/11407317.html