Skip to main content

Reverse each word in a string

Here given code implementation process.

// Java program
// Reverse individual words of the sentence

//Stack Node
class Node
{
	public char data;
	public Node next;
	public Node(char data)
	{
		this.data = data;
		this.next = null;
	}
}
//Define custom stack and its operation
class MyStack
{
	public Node top;
	public MyStack()
	{
		this.top = null;
	}
	//Add a new element in stack
	public void push(char data)
	{
		//Make a new stack node
		Node new_node = new Node(data);
		if (new_node != null)
		{
			new_node.next = this.top;
			this.top = new_node;
		}
		else
		{
			System.out.print("Memory overflow\n");
		}
	}
	//remove a top element in stack
	public void pop()
	{
		if (this.top != null)
		{
			this.top = this.top.next;
		}
	}
	//check that whether stack is empty or not
	public boolean is_empty()
	{
		if (this.top != null)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	//Used to get top element of stack
	public char peek()
	{
		if (this.top != null)
		{
			return this.top.data;
		}
		else
		{
			return ' ';
		}
	}
}
class ReverseStringWord
{
	// Reverse the given string words
	public String reversing_word(String text)
	{
		int size = text.length();
		//Auxiliary variable which is used to store result of string
		String result = "";
		//Create an stack
		MyStack stack = new MyStack();
		// Add element into stack
		for (int i = 0; i < size; i++)
		{
			if (text.charAt(i) == ' ')
			{
				// iterating the stack elements until if not empty
				while (stack.is_empty() == false)
				{
					//Get top element
					result += stack.peek();
					//remove current top
					stack.pop();
				}
				result += " ";
			}
			else
			{
				//Add element into stack
				stack.push(text.charAt(i));
			}
		}
		// When last words are exist in stack
		while (stack.is_empty() == false)
		{
			//Get top element
			result += stack.peek();
			//remove current top
			stack.pop();
		}
		return result;
	}
	public static void main(String[] args)
	{
		ReverseStringWord obj = new ReverseStringWord();
		String text = "This is a simple words";
		System.out.print(" Before Reverse : [" + text + "]");
		text = obj.reversing_word(text);
		System.out.print("\n After Reverse  : [" + text + "]");
		text = "It's to good ";
		System.out.print("\n Before Reverse : [" + text + "]");
		text = obj.reversing_word(text);
		System.out.print("\n After Reverse  : [" + text + "]");
	}
}

Output

 Before Reverse : [This is a simple words]
 After Reverse  : [sihT si a elpmis sdrow]
 Before Reverse : [It's to good ]
 After Reverse  : [s'tI ot doog ]
//Include header file
#include <iostream>
#include<string.h>

using namespace std;

// C++ program
// Reverse individual words of the sentence

//Stack Node
class Node
{
	public: 
    char data;
	Node *next;
	Node(char data)
	{
		this->data = data;
		this->next = NULL;
	}
};
//Define custom stack and its operation
class MyStack
{
	public: 
    Node *top;
	MyStack()
	{
		this->top = NULL;
	}
	//Add a new element in stack
	void push(char data)
	{
		//Make a new stack node
		Node *new_node = new Node(data);
		if (new_node != NULL)
		{
			new_node->next = this->top;
			this->top = new_node;
		}
		else
		{
			cout << "Memory overflow\n";
		}
	}
	//remove a top element in stack
	void pop()
	{
		if (this->top != NULL)
		{
			this->top = this->top->next;
		}
	}
	//check that whether stack is empty or not
	bool is_empty()
	{
		if (this->top != NULL)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	//Used to get top element of stack
	char peek()
	{
		if (this->top != NULL)
		{
			return this->top->data;
		}
		else
		{
			return ' ';
		}
	}
};
class ReverseStringWord
{
	public:
		// Reverse the given string words
		string reversing_word(string text)
		{
			int size = text.size();
			//Auxiliary variable which is used to store result of string
			string result = "";
			//Create an stack
			MyStack stack = MyStack();
			// Add element into stack
			for (int i = 0; i < size; i++)
			{
				if (text[i] == ' ')
				{
					// iterating the stack elements until if not empty
					while (stack.is_empty() == false)
					{
						//Get top element
						result += stack.peek();
						//remove current top
						stack.pop();
					}
					result += " ";
				}
				else
				{
					//Add element into stack
					stack.push(text[i]);
				}
			}
			// When last words are exist in stack
			while (stack.is_empty() == false)
			{
				//Get top element
				result += stack.peek();
				//remove current top
				stack.pop();
			}
			return result;
		}
};
int main()
{
	ReverseStringWord obj = ReverseStringWord();
	string text = "This is a simple words";
	cout << " Before Reverse : [" << text << "]";
	text = obj.reversing_word(text);
	cout << "\n After Reverse  : [" << text << "]";
	text = "It's to good ";
	cout << "\n Before Reverse : [" << text << "]";
	text = obj.reversing_word(text);
	cout << "\n After Reverse  : [" << text << "]";
	return 0;
}

Output

 Before Reverse : [This is a simple words]
 After Reverse  : [sihT si a elpmis sdrow]
 Before Reverse : [It's to good ]
 After Reverse  : [s'tI ot doog ]
//Include namespace system
using System;

// C# program
// Reverse individual words of the sentence

//Stack Node
class Node
{
	public char data;
	public Node next;
	public Node(char data)
	{
		this.data = data;
		this.next = null;
	}
}
//Define custom stack and its operation
class MyStack
{
	public Node top;
	public MyStack()
	{
		this.top = null;
	}
	//Add a new element in stack
	public void push(char data)
	{
		//Make a new stack node
		Node new_node = new Node(data);
		if (new_node != null)
		{
			new_node.next = this.top;
			this.top = new_node;
		}
		else
		{
			Console.Write("Memory overflow\n");
		}
	}
	//remove a top element in stack
	public void pop()
	{
		if (this.top != null)
		{
			this.top = this.top.next;
		}
	}
	//check that whether stack is empty or not
	public Boolean is_empty()
	{
		if (this.top != null)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	//Used to get top element of stack
	public char peek()
	{
		if (this.top != null)
		{
			return this.top.data;
		}
		else
		{
			return ' ';
		}
	}
}
class ReverseStringWord
{
	// Reverse the given string words
	public String reversing_word(String text)
	{
		int size = text.Length;
		//Auxiliary variable which is used to store result of string
		String result = "";
		//Create an stack
		MyStack stack = new MyStack();
		// Add element into stack
		for (int i = 0; i < size; i++)
		{
			if (text[i] == ' ')
			{
				// iterating the stack elements until if not empty
				while (stack.is_empty() == false)
				{
					//Get top element
					result += stack.peek();
					//remove current top
					stack.pop();
				}
				result += " ";
			}
			else
			{
				//Add element into stack
				stack.push(text[i]);
			}
		}
		// When last words are exist in stack
		while (stack.is_empty() == false)
		{
			//Get top element
			result += stack.peek();
			//remove current top
			stack.pop();
		}
		return result;
	}
	public static void Main(String[] args)
	{
		ReverseStringWord obj = new ReverseStringWord();
		String text = "This is a simple words";
		Console.Write(" Before Reverse : [" + text + "]");
		text = obj.reversing_word(text);
		Console.Write("\n After Reverse  : [" + text + "]");
		text = "It's to good ";
		Console.Write("\n Before Reverse : [" + text + "]");
		text = obj.reversing_word(text);
		Console.Write("\n After Reverse  : [" + text + "]");
	}
}

Output

 Before Reverse : [This is a simple words]
 After Reverse  : [sihT si a elpmis sdrow]
 Before Reverse : [It's to good ]
 After Reverse  : [s'tI ot doog ]
<?php
// Php program
// Reverse individual words of the sentence

//Stack Node
class Node
{
	public $data;
	public $next;

	function __construct($data)
	{
		$this->data = $data;
		$this->next = null;
	}
}
//Define custom stack and its operation
class MyStack
{
	public $top;

	function __construct()
	{
		$this->top = null;
	}
	//Add a new element in stack
	public	function push($data)
	{
		//Make a new stack node
		$new_node = new Node($data);
		if ($new_node != null)
		{
			$new_node->next = $this->top;
			$this->top = $new_node;
		}
		else
		{
			echo "Memory overflow\n";
		}
	}
	//remove a top element in stack
	public	function pop()
	{
		if ($this->top != null)
		{
			$this->top = $this->top->next;
		}
	}
	//check that whether stack is empty or not
	public	function is_empty()
	{
		if ($this->top != null)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	//Used to get top element of stack
	public	function peek()
	{
		if ($this->top != null)
		{
			return $this->top->data;
		}
		else
		{
			return ' ';
		}
	}
}
class ReverseStringWord
{
	// Reverse the given string words
	public	function reversing_word($text)
	{
		$size = strlen($text);
		//Auxiliary variable which is used to store result of string
		$result = "";
		//Create an stack
		$stack = new MyStack();
		// Add element into stack
		for ($i = 0; $i < $size; $i++)
		{
			if ($text[$i] == ' ')
			{
				// iterating the stack elements until if not empty
				while ($stack->is_empty() == false)
				{
					//Get top element
					$result .= $stack->peek();
					//remove current top
					$stack->pop();
				}
				$result .= " ";
			}
			else
			{
				//Add element into stack
				$stack->push($text[$i]);
			}
		}
		// When last words are exist in stack
		while ($stack->is_empty() == false)
		{
			//Get top element
			$result .= $stack->peek();
			//remove current top
			$stack->pop();
		}
		return $result;
	}
}

function main()
{
	$obj = new ReverseStringWord();
	$text = "This is a simple words";
	echo " Before Reverse : [". $text ."]";
	$text = $obj->reversing_word($text);
	echo "\n After Reverse  : [". $text ."]";
	$text = "It's to good ";
	echo "\n Before Reverse : [". $text ."]";
	$text = $obj->reversing_word($text);
	echo "\n After Reverse  : [". $text ."]";
}
main();

Output

 Before Reverse : [This is a simple words]
 After Reverse  : [sihT si a elpmis sdrow]
 Before Reverse : [It's to good ]
 After Reverse  : [s'tI ot doog ]
// Node Js program
// Reverse individual words of the sentence

//Stack Node
class Node
{
	constructor(data)
	{
		this.data = data;
		this.next = null;
	}
}
//Define custom stack and its operation
class MyStack
{
	constructor()
	{
		this.top = null;
	}
	//Add a new element in stack
	push(data)
	{
		//Make a new stack node
		var new_node = new Node(data);
		if (new_node != null)
		{
			new_node.next = this.top;
			this.top = new_node;
		}
		else
		{
			process.stdout.write("Memory overflow\n");
		}
	}
	//remove a top element in stack
	pop()
	{
		if (this.top != null)
		{
			this.top = this.top.next;
		}
	}
	//check that whether stack is empty or not
	is_empty()
	{
		if (this.top != null)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	//Used to get top element of stack
	peek()
	{
		if (this.top != null)
		{
			return this.top.data;
		}
		else
		{
			return ' ';
		}
	}
}
class ReverseStringWord
{
	// Reverse the given string words
	reversing_word(text)
	{
		var size = text.length;
		//Auxiliary variable which is used to store result of string
		var result = "";
		//Create an stack
		var stack = new MyStack();
		// Add element into stack
		for (var i = 0; i < size; i++)
		{
			if (text[i] == ' ')
			{
				// iterating the stack elements until if not empty
				while (stack.is_empty() == false)
				{
					//Get top element
					result += stack.peek();
					//remove current top
					stack.pop();
				}
				result += " ";
			}
			else
			{
				//Add element into stack
				stack.push(text[i]);
			}
		}
		// When last words are exist in stack
		while (stack.is_empty() == false)
		{
			//Get top element
			result += stack.peek();
			//remove current top
			stack.pop();
		}
		return result;
	}
}

function main()
{
	var obj = new ReverseStringWord();
	var text = "This is a simple words";
	process.stdout.write(" Before Reverse : [" + text + "]");
	text = obj.reversing_word(text);
	process.stdout.write("\n After Reverse  : [" + text + "]");
	text = "It's to good ";
	process.stdout.write("\n Before Reverse : [" + text + "]");
	text = obj.reversing_word(text);
	process.stdout.write("\n After Reverse  : [" + text + "]");
}
main();

Output

 Before Reverse : [This is a simple words]
 After Reverse  : [sihT si a elpmis sdrow]
 Before Reverse : [It's to good ]
 After Reverse  : [s'tI ot doog ]
#  Python 3 program
#  Reverse individual words of the sentence

# Stack Node
class Node :
	
	def __init__(self, data) :
		self.data = data
		self.next = None
	

# Define custom stack and its operation
class MyStack :
	
	def __init__(self) :
		self.top = None
	
	# Add a new element in stack
	def push(self, data) :
		# Make a new stack node
		new_node = Node(data)
		if (new_node != None) :
			new_node.next = self.top
			self.top = new_node
		else :
			print("Memory overflow\n", end = "")
		
	
	# remove a top element in stack
	def pop(self) :
		if (self.top != None) :
			self.top = self.top.next
		
	
	# check that whether stack is empty or not
	def is_empty(self) :
		if (self.top != None) :
			return False
		else :
			return True
		
	
	# Used to get top element of stack
	def peek(self) :
		if (self.top != None) :
			return self.top.data
		else :
			return ' '
		
	

class ReverseStringWord :
	#  Reverse the given string words
	def reversing_word(self, text) :
		size = len(text)
		# Auxiliary variable which is used to store result of string
		result = ""
		# Create an stack
		stack = MyStack()
		i = 0
		#  Add element into stack
		while (i < size) :
			if (text[i] == ' ') :
				#  iterating the stack elements until if not empty
				while (stack.is_empty() == False) :
					# Get top element
					result += stack.peek()
					# remove current top
					stack.pop()
				
				result += " "
			else :
				# Add element into stack
				stack.push(text[i])
			
			i += 1
		
		#  When last words are exist in stack
		while (stack.is_empty() == False) :
			# Get top element
			result += stack.peek()
			# remove current top
			stack.pop()
		
		return result
	

def main() :
	obj = ReverseStringWord()
	text = "This is a simple words"
	print(" Before Reverse : [{0}]".format(text), end = "")
	text = obj.reversing_word(text)
	print("\n After Reverse  : [{0}]".format(text), end = "")
	text = "It's to good "
	print("\n Before Reverse : [{0}]".format(text), end = "")
	text = obj.reversing_word(text)
	print("\n After Reverse  : [{0}]".format(text), end = "")

if __name__ == "__main__": main()

Output

 Before Reverse : [This is a simple words]
 After Reverse  : [sihT si a elpmis sdrow]
 Before Reverse : [It's to good ]
 After Reverse  : [s'tI ot doog ]
#  Ruby program
#  Reverse individual words of the sentence

# Stack Node
class Node  
	# Define the accessor and reader of class Node  
	attr_reader :data, :next
	attr_accessor :data, :next
 
	
	def initialize(data) 
		self.data = data
		self.next = nil
	end

end

# Define custom stack and its operation
class MyStack  
	# Define the accessor and reader of class MyStack  
	attr_reader :top
	attr_accessor :top
 
	
	def initialize() 
		self.top = nil
	end

	# Add a new element in stack
	def push(data) 
		# Make a new stack node
		new_node = Node.new(data)
		if (new_node != nil) 
			new_node.next = self.top
			self.top = new_node
		else 
			print("Memory overflow\n")
		end

	end

	# remove a top element in stack
	def pop() 
		if (self.top != nil) 
			self.top = self.top.next
		end

	end

	# check that whether stack is empty or not
	def is_empty() 
		if (self.top != nil) 
			return false
		else 
			return true
		end

	end

	# Used to get top element of stack
	def peek() 
		if (self.top != nil) 
			return self.top.data
		else 
			return ' '
		end

	end

end

class ReverseStringWord 
	#  Reverse the given string words
	def reversing_word(text) 
		size = text.length()
		# Auxiliary variable which is used to store result of string
		result = ""
		# Create an stack
		stack = MyStack.new()
		i = 0
		#  Add element into stack
		while (i < size) 
			if (text[i] == ' ') 
				#  iterating the stack elements until if not empty
				while (stack.is_empty() == false) 
					# Get top element
					result += stack.peek()
					# remove current top
					stack.pop()
				end

				result += " "
			else 
				# Add element into stack
				stack.push(text[i])
			end

			i += 1
		end

		#  When last words are exist in stack
		while (stack.is_empty() == false) 
			# Get top element
			result += stack.peek()
			# remove current top
			stack.pop()
		end

		return result
	end

end

def main() 
	obj = ReverseStringWord.new()
	text = "This is a simple words"
	print(" Before Reverse : [", text ,"]")
	text = obj.reversing_word(text)
	print("\n After Reverse  : [", text ,"]")
	text = "It's to good "
	print("\n Before Reverse : [", text ,"]")
	text = obj.reversing_word(text)
	print("\n After Reverse  : [", text ,"]")
end

main()

Output

 Before Reverse : [This is a simple words]
 After Reverse  : [sihT si a elpmis sdrow]
 Before Reverse : [It's to good ]
 After Reverse  : [s'tI ot doog ]
// Scala program
// Reverse individual words of the sentence

//Stack Node
class Node(var data: Character,
	var next: Node)
{
	def this(data: Char)
	{
		this(data, null);
	}
}
//Define custom stack and its operation
class MyStack(var top: Node)
{
	def this()
	{
		this(null);
	}
	//Add a new element in stack
	def push(data: Char): Unit = {
		//Make a new stack node
		var new_node: Node = new Node(data);
		if (new_node != null)
		{
			new_node.next = this.top;
			this.top = new_node;
		}
		else
		{
			print("Memory overflow\n");
		}
	}
	//remove a top element in stack
	def pop(): Unit = {
		if (this.top != null)
		{
			this.top = this.top.next;
		}
	}
	//check that whether stack is empty or not
	def is_empty(): Boolean = {
		if (this.top != null)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	//Used to get top element of stack
	def peek(): Char = {
		if (this.top != null)
		{
			return this.top.data;
		}
		else
		{
			return ' ';
		}
	}
}
class ReverseStringWord
{
	// Reverse the given string words
	def reversing_word(text: String): String = {
		var size: Int = text.length();
		//Auxiliary variable which is used to store result of string
		var result: String = "";
		//Create an stack
		var stack: MyStack = new MyStack();
		var i: Int = 0;
		// Add element into stack
		while (i < size)
		{
			if (text(i) == ' ')
			{
				// iterating the stack elements until if not empty
				while (stack.is_empty() == false)
				{
					//Get top element
					result += stack.peek();
					//remove current top
					stack.pop();
				}
				result += " ";
			}
			else
			{
				//Add element into stack
				stack.push(text(i));
			}
			i += 1;
		}
		// When last words are exist in stack
		while (stack.is_empty() == false)
		{
			//Get top element
			result += stack.peek();
			//remove current top
			stack.pop();
		}
		return result;
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var obj: ReverseStringWord = new ReverseStringWord();
		var text: String = "This is a simple words";
		print(" Before Reverse : [" + text + "]");
		text = obj.reversing_word(text);
		print("\n After Reverse  : [" + text + "]");
		text = "It's to good ";
		print("\n Before Reverse : [" + text + "]");
		text = obj.reversing_word(text);
		print("\n After Reverse  : [" + text + "]");
	}
}

Output

 Before Reverse : [This is a simple words]
 After Reverse  : [sihT si a elpmis sdrow]
 Before Reverse : [It's to good ]
 After Reverse  : [s'tI ot doog ]
// Swift 4 program
// Reverse individual words of the sentence

//Stack Node
class Node
{
	var data: Character;
	var next: Node? ;
	init(_ data: Character)
	{
		self.data = data;
		self.next = nil;
	}
}
//Define custom stack and its operation
class MyStack
{
	var top: Node? ;
	init()
	{
		self.top = nil;
	}
	//Add a new element in stack
	func push(_ data: Character)
	{
		//Make a new stack node
		let new_node: Node? = Node(data);
		if (new_node != nil)
		{
			new_node!.next = self.top;
			self.top = new_node;
		}
		else
		{
			print("Memory overflow\n", terminator: "");
		}
	}
	//remove a top element in stack
	func pop()
	{
		if (self.top != nil)
		{
			self.top = self.top!.next;
		}
	}
	//check that whether stack is empty or not
	func is_empty() -> Bool
	{
		if (self.top != nil)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	//Used to get top element of stack
	func peek() -> Character
	{
		if (self.top != nil)
		{
			return self.top!.data;
		}
		else
		{
			return " ";
		}
	}
}
class ReverseStringWord
{
	// Reverse the given string words
	func reversing_word(_ text: String) -> String
	{
		let size: Int = text.count;
		//Auxiliary variable which is used to store result of string
		var result: String = "";
		//Create an stack
		let stack: MyStack = MyStack();
		var i: Int = 0;
      	var data : Character;
		// Add element into stack
		while (i < size)
		{
            data = Array(text)[i];
			if (data == " ")
			{
				// iterating the stack elements until if not empty
				while (stack.is_empty() == false)
				{
					//Get top element
					result +=  String(stack.peek());
					//remove current top
					stack.pop();
				}
				result += " ";
			}
			else
			{
				//Add element into stack
				stack.push(data);
			}
			i += 1;
		}
		// When last words are exist in stack
		while (stack.is_empty() == false)
		{
			//Get top element
			result += String(stack.peek());
			//remove current top
			stack.pop();
		}
		return result;
	}
}
func main()
{
	let obj: ReverseStringWord = ReverseStringWord();
	var text: String = "This is a simple words";
	print(" Before Reverse : [\(text)]", terminator: "");
	text = obj.reversing_word(text);
	print("\n After Reverse  : [\(text)]", terminator: "");
	text = "It\"s to good ";
	print("\n Before Reverse : [\(text)]", terminator: "");
	text = obj.reversing_word(text);
	print("\n After Reverse  : [\(text)]", terminator: "");
}
main();

Output

 Before Reverse : [This is a simple words]
 After Reverse  : [sihT si a elpmis sdrow]
 Before Reverse : [It"s to good ]
 After Reverse  : [s"tI ot doog ]




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment