Reverse Strings Without Changing the Order of Words in a Sentence

Reverse strings without changing the order of words in a sentence

Use this:

var str = "Welcome to my Website !";
alert(str.split("").reverse().join("").split(" ").reverse().join(" "));

Reverse each word in string without changing word order

Try something like this.

function wordsReverser(string){
return string.split("").reverse().join("").split(" ").reverse().join(" ")
}

console.log(wordsReverser('New string, same results.'));

Reversing a sentence in Java without changing the character order using recursion

Try this:

  • you search for the last space "Cat Is Running"
  • at the first iteration SpaceIndex = 6
  • you print the part after the space which is "Running" and you call recurive
    the same method without that part ("Cat Is")
  • At the last iteration when space is not found you just output the
    string what you have.
public static void main(String[] args) {
String sentence = "Cat Is Running";
reverse(sentence);
}

public static void reverse(String str) {
int spaceIndex = str.lastIndexOf(" ");
if(spaceIndex == -1){
System.out.print(str);
return;
}
System.out.print(str.substring(spaceIndex+1) + " ");
reverse(str.substring(0,spaceIndex));
}

How to reverse words in a string instead of reversing the whole string?

you need to split the string by space

function reverseInPlace(str) {  var words = [];  words = str.match(/\S+/g);  var result = "";  for (var i = 0; i < words.length; i++) {     result += words[i].split('').reverse().join('') + " ";  }  return result}console.log(reverseInPlace("abd fhe kdj"))

Reverse order of words in a sentence without using built in functions

<?php

$str = "My Name is Fred";
$i = 0;
while( $d = $str[$i] )
{
if( $d == " "){

$out = " ".$temp.$out;
$temp = "";
}else{
$temp.=$d;

}
$i++;
}
echo $temp.$out;
?>

Python reverse each word in a sentence without inbuilt function python while preserve order

The following works without managing indices:

def reverseString(someString):
result = crnt = ""
for c in someString:
if c != " ":
crnt = c + crnt # build the reversed current token
elif crnt: # you only want to do anything for the first space of many
if result:
result += " " # append a space first
result += crnt # append the current token
crnt = "" # and reset it
if crnt:
result += " " + crnt
return result

reverseString(" my name is scheven ")
# 'ym eman si nevehcs'


Related Topics



Leave a reply



Submit