Reversing a sentence word by word

Start tokenizing the line from the last character and continue to the first character. Keep one pointer anchored at the base of the current word, and another pointed which will decrease while a word start is not found. When you find a word start while scanning like this, print from the word start pointer to the word end anchor. Update the word end anchor to the previous character of the current word start char.

You might want to skip the blankspace characters while scanning.

UPDATE

This is a quick implementation:

#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define MAX_BUF 256

void show_string (char *str, int i, int n)
{
  while (i <= n)
  {
    printf ("%c", str[i]);
    i++;
  }
}

int main (void)
{
  char str[MAX_BUF];
  int end_anchor, start_ptr;
  int state;

  printf ("nEnter a string: ");
  scanf (" %[^n]", str);

  start_ptr = strlen (str) - 1;

  end_anchor = start_ptr;
  state = 0;
  while (start_ptr >= -1)
  {
    switch (state)
    {
      case 0:
             if ((!isspace (str[start_ptr]) && (start_ptr >= 0)))
             {
               start_ptr--;
             }
             else
             {
               state = 1;
             }
             break;

      case 1:
             show_string (str, start_ptr + 1, end_anchor);
             state = 2;
             start_ptr--;
             printf (" ");
             break;

      case 2:
             if (!isspace (str[start_ptr]))
             {
               state = 0;
               end_anchor = start_ptr;
             }
             else
             {
               start_ptr--;
             }
             break;
    }
  }


  printf ("n");
  return 0;
}

The end_anchor points to each end word, and the start_ptr finds the start of the word of which the end is held by end_anchor. When we find a word start (by blankspace characters or start_ptr = -1), we print all the characters from start_ptr + 1 to end_anchor. The + 1 is because of the implementation: start_ptr points to the blankspace character, and the print routine will print all the characters from i to n. Once we have detected one blank space we print it and we skip adjacent blankspaces (in case 2) and preserve only one which is manually printed. Once a non blankspace is detected, we have got another word end, for which we set the end_anchor to this index in the case 2, and set state = 0 , so that we can search for the word start again.

Problem

Write a program to reverse an English sentence word by word not character by character. For example if the sentence is “I love Pizza so much” the program should print “much so Pizza love I”

Solution

One solution is to split the sentence into tokens using the space character as the separator then print the tokens in reverse order

Code

Here is how to do that in Perl

#!/usr/bin/perl

# Input sentence

$sentence = «I love Pizza so much»;

# Split the sentence into tokens

# The first parameter is the separator

@tokens = split (» «, $sentence);

# Print the tokens in reverse order

# $#tokens is the Perl syntax to get the tokens array size

for ($i = $#tokens; $i >= 0; $i—)

{

   print $tokens[$i] . » «;

}

About Author

Mohammed Abualrob

Software Engineer @ Cisco

Summary: In this programming example, we will learn different ways to reverse a given sentence word by word in Java.

Example:

Input:  I am a programmer
Output: programmer a am I

The problem is to reverse a sentence without reversing its individual words.

We can solve this by extracting every word from the sentence and concatenate them in reverse order.

Here are two such ways to do so in Java:

Method 1: Using Loop

With the help of indexOf() and substring() methods, we extract the words from the input sentence and concatenate them to the reverse string in reverse order.

import java.util.Scanner;
 
public class Main {
  public static void main(String args[]){
    Scanner in =new Scanner(System.in);
    
    //Input sentence
    System.out.print("Enter a sentence: ");
    String str = in.nextLine();

    //Append whitespace for the extraction of last word
    str += " ";

    String reversed = "";

    //repeat until no word is left
    while(str.indexOf(" ") != -1){
      //Extract word
      int idx = str.indexOf(" ");
      String word = str.substring(0, idx);

      //Concatenate in reverse order
      reversed = word + " "+ reversed;

      //Remove word from the sentence
      str = str.substring(idx+1);
    }
   
    //Output the reverse
    System.out.print("Reverse: ");
    System.out.println(reversed);
  }
}

Output:

Enter a sentence: how are you
Reverse: you are how

Every time we append a word to the reverse string, we remove it from the input sentence.

We use the ‘while’ loop to repeat the process until no word in the input sentence is left to process.

Method 2: Using Recursion

What we did in the previous method can also be implemented using the recursion technique.

import java.util.Scanner;
 
public class Main {
  public static void main(String args[]){
    Scanner in =new Scanner(System.in);

    //Input sentence
    System.out.print("Enter a Sentence: ");
    String sentence = in.nextLine();

    //Reverse by calling the recursive method
    String reversed = reverse(sentence);

    //output the reversed word
    System.out.print("Reverse: ");
    System.out.println(reversed);
  }

  public static String reverse(String str){
    int idx = str.indexOf(" ");
    //Base condition - when str has only one word
    if(idx == -1)
      return str;
    
    //return after concatenating in reverse order
    return reverse(str.substring(idx+1)) +" "+ str.substring(0, idx);
  }
}

Output:

Enter a Sentence: Hello World!
Reverse: World! Hello

On each recursive call, we extract a word from the front of the sentence using str.substring(0, idx) and concatenate it to the reversed result (i.e., reverse(str.substring(idx+1))) in the reverse order.

The recursive call reverse(str.substring(idx+1)) passes the remaining sentence as an argument that in turn extracts the word from the front and concatenates it in reversed order.

These are the two methods using which we can reverse a sentence without reversing its individual words in Java programming language.

In this python programming article, we are going to learn

  • program to reverse a sentence word by word in python

Program to reverse a sentence word by word in Python

The program is as follows:

# Owner : TutorialsInhand Author : Devjeet Roy

sentence = input("Enter sentence: ").strip()
sentence = sentence.lower()

word_list = sentence.split(" ")

reversed_word_list = word_list[::-1]

reversed_sentence = " ".join(reversed_word_list)

print("The reversed sentence is:",reversed_sentence)

The output of the program is as follows:

PS C:UsersDEVJEETDesktoptutorialsInHand> python code.py
Enter sentence: I love python programming
The reversed sentence is: programming python love i

Few important tips about the program

1. We take the string input from the user and convert it to lowercase.

2. Then we split the sentence word by word and make a list out of it.

3. We have then reversed the list using negative indexing.

4. We have then joined the reversed list to a string which is actually our reversed sentence.

reverse-a-sentence-word-by-word-in-python

Would you like to see your article here on tutorialsinhand.
Join Write4Us program by tutorialsinhand.com

About the Author

Devjeet Roy
Full Stack Web Developer & Blockchain Enthusiast

Page Views :

  

Published Date :
Oct 13,2022  

A simple backwards text converter.

Reversing Your Text

This is a simple translator I made that simply reverses your words or phrases. Note that you may be looking for a translator which mirrors your text (oƨ ɘʞil) — if so, click that link.

The way it does it is quite simple. Since you’re viewing this online in your browser, JavaScript is used as follows:

> «my example text».split(«»).reverse().join(«»);

The letters of the string are first split into individual array components, then the handy «String.reverse()» method is used, then we join the elements back up into a string, resulting in the same characters, but i a reverse or backwards direction.

Reverse Words

Writing text backwards is a great way to add a very light layer of cryptography to the things you write — reverse the word and character order, and make it slightly messy, and you may find that no one can understand it at all! You can also make other rules like leaving out the last vowel or something like that to make it harder.

A few quick examples of what this translator produces:

  • yellow = wolley
  • dog = god
  • sheep = peehs
  • park = krap
  • racecar = racecar
  • supercallifragilisticexpiallidocious = suoicodillaipxecitsiligarfillacrepus

Try reverse a word or phrase and post it in the comments below :)

I hope this little online tool helps you with whatever you’re doing. If you’ve got any suggestions for how I could improve this translator please let me know by putting them in the suggestions form. Thanks! :)

#include <stdio.h>

int main(void)
{
  int i,j;
  int wordstart = -1;
  int wordend = -1;
  char words[]= "this is a test";
  char temp;

  // Reverse each word
  for (i = 0; i < strlen(words); ++i)
  {
    wordstart = -1;
    wordend = -1;
    if(words[i] != ' ') 
      wordstart = i;
    for (j = wordstart; j < strlen(words); ++j)
    {
      if(words[j] == ' ')
      {
        wordend = j - 1;
        break;
      }
    }
    if(wordend == -1)
      wordend = strlen(words);
    for (j = wordstart ; j <= (wordend - wordstart) / 2; ++j)
    {
      temp = words[j];
      words[j] = words[wordend - (j - wordstart)];
      words[wordend - (j - wordstart)] = temp;
    }
    i = wordend;
    printf("reversed string is %s:", words);
  }
}

I tried in this way but i am getting this output:
siht is a test
my expected output is:
test a is this

I would appreciate if some one could come with a different approach for which time complexity is very less or correct me if it is the right approach. Thanks

DESCRIPTION:

We need to reverse a sentence word by word.

For example,

original sentence: Welcome to cppsecrets

reversed sentence: cppsecrets to Welcome

LOGIC:

To reverse a sentence we follow:

Step 1: We need to create an empty string (let it be word) & traverse original sentence from left to right.

Step 2: We will keep on adding sentence[i] to word till sentence[i]!=’ ‘.

Step 3: If we get space push ‘word’ onto stack and again make ‘word’ string empty.

Step 4: At last pop all elements from stack while printing them.

CODE:

#include<iostream>
#include<stack>
using namespace std;int main(){
stack<string> s;
string sentence=«Hey, how are you?»,word=«»;
cout<<«Original sentence is: «<<sentence;
int i;

//loop continues till we reach end of statement
for(i=0;sentence[i]!=‘�’;i++){

//if we get space push word onto stack and update word to » again
if(sentence[i]==‘ ‘){

s.push(word);

//updating word to » again after getting space and pushing prev word in stack
word=
«»;

continue;
}


word+=sentence[i];

}
s.push(word);

cout<<«nReverse sentence is: «;
while(!s.empty()){
cout<<s.top()<<» «;
s.pop();
}
return 0;
}

OUTPUT:


Reverse Text Generator


Reverse text is formed by writing in the direction that for a given language is the reverse of the natural way, so the result is the mirror image of normal writing. It appears normal when reflected in a mirror. It is sometimes used as a code that is extremely primitive. A common modern use of mirror writing can be found on the ambulance front, where the word «AMBULANCE» is often written in the very large mirrored text so drivers can see the word in their rear-view mirror the right way around.

Some people can produce mirrored text handwritten. In this way, in particular, Leonardo da Vinci wrote most of his personal notes. Mirror writing calligraphy has been popular in the Ottoman Empire, where mystical associations have often been carried.

How to Use Reverse Text?

Copy paste the text in the box that you want to reverse. Select the best option according to your need. Our tool provides the following options:

  • Reverse Text
  • Reverse Wording
  • Reverse each Word’s Lettering

Backwards text can reverse words, flip words, and reverse letters with one click. If you want to count how many words you have flipped, for this, you can use word count tool separately. Apart from counting and words backwards, you can also use word combiner for joining reverse words together for domain name, business name or fun game in a more creative way.


How Does Text Reverser Work?

As mentioned above, our backwards text generator comes with three options i.e., Reverse Text, Reverse Wording and Reverse each Word’s Lettering.

All these options differ with each other at some point. Let’s see the difference in them with example. Suppose this is the text that you want to reverse:

«Enter your text then click «reverse, flip, reverse wording, reverse each word’s lettering, upside down» and get your needed result.»

When you will select «backwards words» option the outcome will be:

«.tluser dedeen ruoy teg dna «nwod edispu ,gnirettel s’drow hcae esrever ,gnidrow esrever ,pilf ,esrever» kcilc neht txet ruoy retnE»

Now if you see, this option reversed the sentence and then reversed the letters of each word.

When you will select «Reverse wording» option the outcome will be:

«.result needed your get and «down upside ,lettering s’word each reverse ,wording reverse ,flip ,reverse» click then text your Enter»

This option keeps the text readable and does not convert «result» into «tluser». It’s because it reverses words only in the sentence.

When you will select «Reverse wording» option the outcome will be:

«Retne ruoy txet neht kcilc «esrever, pilf, esrever gnidrow, esrever hcae drow’s gnirettel, edispu nwod» dna teg ruoy dedeen tluser.»

The third option of word reverser tool works perfectly by reversing each word’s letter as you can see in the given example. This option does not change the sentence structure but only reverse the text’s spelling.

Simply put, our reverse words tool works by first reversing the direction of your characters and then attempting to find a Unicode character individually that best reverses each of the characters you type.


Reverse Text Tool Uses

There are multiple possible uses of reverse text generator, for example, it can be used for encoding, in ambulance case, and for important data security. Let’s dive into the more details of the uses of the tool.

Ambulance Mirror Writing

You will definitely notice when you see an ambulance on the street that the word’ AMBULANCE’ is spelled backward, like «ECNALUBMA.» Do you know why?

The main reason for this is the readability of the words for drivers when they will see an ambulance behind their vehicles. The word «Ambulance» is written backward on the front of the vehicles so that drivers in front can read the word easily from their rearview mirrors, especially in an emergency situation.

Data Encoding

Apart from the emergency cases and ambulance backward writing, text reverser can be used for data encoding. Data security has always been a priority for giant companies since the beginning of the digital era. The tech companies even a common internet user has the privacy that shouldn’t be breached at any cost.

Text reverser can save users from passcode stealing by generating strong passwords. Generally, hackers guess or use the most common passwords to hack Google, Twitter, Instagram, and Facebook profiles. Having a strong passcode can reduce the risk because it would be hard for them to guess the reverse text password. Hence, you are in safe hands!

Fun Games

Children love to play fun games specifically when they are in the age of exploring new words, phrases, and sentences. Reverse text is a good practice to make your children learn new words. For example, the word «words» can be spelled «sword» backward.

i love you in reverse text is «uoy evol i»

Similarly, for the letters recognition and fancy texts, you can use our small text generator tool. It creates stylish, fancy, and decorated text for the given text.


Reverse Text in Past

Mirror writing or reverse writing is not something new. It has been used by some notable writers, painters, and calligraphers to create amazing artwork.

Leonardo da Vinci

Most of Leonardo da Vinci personal notes were written in mirror writing, using standard writing. Leonardo’s purpose for this practice remains unknown, although it has suggested several possible reasons. Writing left-handed from left to right, for example, would have been messy because just putting the ink would smear as his hand moved across it. Writing backward would avoid this kind of smudging. Nowadays, the ink is not a problem anymore in writing reverse. We wonder, what would happen if he had been alive in the digital era? Maybe he would have been using our reverse text generator for his personal notes.

An alternative theory is that the process of turning the language object into memory before it is placed on paper and rotated before it is read back, is a method of strengthening learning. From this theory, the use of boustrophedonic writing can result, especially in public codes, in making the text in the reader more reminiscent.

Matteo Zaccolini

Matteo Zaccolini had written his original four-volume treatise on optic, color and perspective in a mirror script in the early 17th century.

Pre-Islamic & Ottoman Empire

During the 18th and 19th centuries, Mirror writing calligraphy was popular among the Bektashi order in the Ottoman Empire, where it often carried mystical associations. The origins of this mirror writing tradition can be traced back to pre-Islamic times in western Arab peninsula rock inscriptions.

Понравилась статья? Поделить с друзьями:
  • Reversed letters in word
  • Reverse words in word for printing
  • Reverse word order in string
  • Reverse word order in english
  • Reverse word in python