简体   繁体   中英

How to reverse initial string and save space order

How to reverse initial string and save space order more correctly than in my solution. I need to transfrom initial string, to do it reversed but keep the same order of spaces as initiall string 'some text with spaces' //=> "seca psht iwtx etemos"

 function test(str, result = "") { let res = str.split('').reverse().join('') for (let i = 0; i < res.length; i++) { if (str[i] === " ") { result += ` ${res[i]}` str[i + 1]; } else if (str[i];== " " && res[i] === " ") { result += "" } else { result += res[i]. } } return result } console.log(test('some text with spaces')) //=> "seca psht iwtx etemos"

You could take a single loop without splitting and get the non space characters from the end and insert spaces if one is found at the actual length of the new string.

 function test(str) { let i = str.length, s = ''; while (i--) { if (str[i] === ' ') continue; while (str[s.length] === ' ') s += ' '; s += str[i]; } return s; } console.log(test('some text with spaces'));

function test(str) { const letters = str.split(""); // make array so we can modify it const spaceIndexes = letters.reduce((arr, letter, index) => { if (letter === " ") arr.push(index); return arr; }, []); const reversed = letters.filter(l => l !== ' ').reverse(); // reverse and delete spaces spaceIndexes.forEach((index) => reversed.splice(index, 0, " ")); // insert spaces at previous places return reversed.join(""); // return as a string }

This will return all non-blank letters in a reverse order with all blanks at the positions of the original string:

 function test(str) { let i=-1,spaces=[]; while ((i=str.indexOf(' ',i+1))>-1) spaces.push(i); // find space positions let res=str.replace(/ /g,'').split('').reverse(); // remove spaces and // turn into array and reverse it spaces.forEach(i=>res.splice(i,0,' ')) // put spaces back into array return res.join(''); // turn array to string and return } let str="let us try this function."; console.log(str); console.log(test(str))

Not exactly sure if there is better solution than this. But the best I could think of for now

The algorithm is

  • Find out the space indexes in the given string
  • Reverse the same sting
  • Add the space as per indexes got above and replace any additional spaces in string

 function test(str) { const mapping = {}; const pattern = /\s+/g; while (match = pattern.exec(str)) { mapping[match.index] = true; } return str.split('').reverse().reduce((acc, cur, index) => { if(mapping[index]) acc += ' '; acc += cur.replace(pattern, ''); return acc; }, ''); } // seca psht iwtx etemos console.log(test('some text with spaces'))

let theString = "some text with spaces";
let spaceArr = []  // we will store spaces position in this array
let pos = 0
let strArr = theString.split(" ")
for(let i=0; i<strArr.length-1; i++){
  spaceArr.push(pos + strArr[i].length)
  pos = pos+1 + strArr[i].length
}
// now lets remove spaces , reverse string, put back orignal spaces 
let res = strArr.join("").split("").reverse().join("").split("")
spaceArr.forEach((item,index)=>{
  res.splice(item,0," ") 
})
console.log(res.join(""))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM