Amazon Interview Question for Testing / Quality Assurances


Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
4
of 4 vote

Python code

sentence = raw_input("Enter String")
sentence = sentence.split()
new_sentence = [word[::-1] for word in sentence]
print ' '.join(str(x) for x in new_sentence)

- Naveen April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Python 1 liner

' '.join((a[::-1] for a in mystr.split()))

- asdasd May 24, 2014 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

Java solution. O(n).

public static String solution(String str) {
		if(str==null) return null;
		
		String result = "";
		String word = "";
		
		for(int i=0;i<str.length();i++) {
			char c = str.charAt(i);
			if(c==' ') {
				result += word + " ";
				word="";
			}
			else {
				word = c + word;
			}
		}
		result += word;
		return result;
	}

- akashgupta April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think this code doesn't consider the situation when the last character of the sentence is space - it will add the last reversed word twice. But this is clean otherwise and gets my vote.

public String revWordsInAGo(String s) {
        if(s == null || s.isEmpty() || s.length() == 1) return s;
        String r = "", w = "";
        char[] c = s.toCharArray();
        int i = 0;
        for(; i < c.length; i++) {
            char ch = c[i];
            if(ch == ' ') {
                r = r + w + ch;
                w = "";
            } else {
                w = ch + w;
            }
        }
        if(c[i - 1] != ' ') { // In case last character is not space
            r = r + w;
        }
        return r;
    }

One can also use 2 pointers pointing to start and end of a word and then reverse that word and move to the next word and so on but I am not sure if it is more efficient than your approach:

public String doReverse(String str) {
        if(str == null || str.length() < 2) return str;
        char[] chars = str.toCharArray();
        int ptr1, ptr2;
        for(int i = 0; i < chars.length;) {
            if(chars[i]!=' ') {
                ptr1 = i;
                for(ptr2 = i + 1; ptr2 < chars.length && chars[ptr2] != ' '; ptr2++) {}
                if(ptr2 != chars.length - 1) --ptr2;
                if(ptr2 - ptr1 > 0) {
                    swapWord(chars, ptr2, ptr1);
                }
                i = ptr2 + 2; // 2 because ptr2 points to last character of current word and next character is a space
            } else {
                ++i;
            }
        }
        return new String(chars);
    }

- Asif Garhi September 02, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Neat but doesn't handle sentences with last character as space well I guess. So my version of your code:

public String revWordsInAGo(String s) {
        if(s == null || s.isEmpty() || s.length() == 1) return s;
        String r = "", w = "";
        char[] c = s.toCharArray();
        int i = 0;
        for(; i < c.length; i++) {
            char ch = c[i];
            if(ch == ' ') {
                r = r + w + ch;
                w = "";
            } else {
                w = ch + w;
            }
        }
        if(c[i - 1] != ' ') { // In case last character is not space
            r = r + w;
        }
        return r;
    }

I initially used 2 pointers to point to start and end of a word and then swap them in place but not sure if this is more efficient than yours:

public String doReverse(String str) {
        if(str == null || str.length() < 2) return str;
        char[] chars = str.toCharArray();
        int ptr1, ptr2;
        for(int i = 0; i < chars.length;) {
            if(chars[i]!=' ') {
                ptr1 = i;
                for(ptr2 = i + 1; ptr2 < chars.length && chars[ptr2] != ' '; ptr2++) {}
                if(ptr2 != chars.length - 1) --ptr2;
                if(ptr2 - ptr1 > 0) {
                    swapWord(chars, ptr2, ptr1); // method not shown for simplicity
                }
                i = ptr2 + 2; // 2 because ptr2 points to last character of current word and next character is a space
            } else {
                ++i;
            }
        }
        return new String(chars);
    }

- Asif Garhi September 02, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is pretty clever and neat, but (in Java) creates way too much string garbage. Every time a char is appended a new string is created discarding an old string.

If that's GC is not a concern, this is a nice solution.

- Runner October 26, 2014 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

My code in Java. Complexity wise its not good i guess. Anyways this is what i thought.

int lengthStr;
		int i;
		String strNew = "";
		char[] cs = new char[10];
		String str = "I am a human being";
		System.out.println("Original String :"+str);
		String[] strArray = str.split("\\s");
		
		for(String s : strArray){
			lengthStr = s.length();
			strNew = strNew + " ";
			for(i=0; i<s.length(); i++){
				cs[i] = s.charAt(lengthStr-1);
				lengthStr--;
				strNew = strNew + cs[i];
			}
		}
		System.out.println("Reversed String :"+strNew.trim());
}

- Shankey April 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

If you will mention your approach in 2 lines as well and then provide code, it would be easy to understand your logic very quickly. :)

- PKT April 24, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

:) I just tried to get the tokens by split method of String. After getting the tokens I got hold of each token and started reversing the alphabets in that particular token. I mean the last alphabet comes to first and so on. Used spaces(whitespace) for each token to be separated. trim() method was used to remove any extra whitespaces .

- Shankey April 25, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Logic: 1:
----I am a human being
1. Reverse the string char by char
----gnieb namuh a ma I
2. Reverse the string words by words
----I ma a namuh gnieb


Logic: 2:
1. Traverse string char by char
2. create token(word) surrounded by space and reverse it
3. where ever space found print is as it is
4. keep forming tokens and reversing it.

- PKT April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Nicely done, thumbs up!

- puneet.sohi April 11, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

here is my PERL program for this problem

#! /usr/bin/perl
my $str="I am human being";
my @words=split(' ',$str);
my $constWord=join(' ',reverse (@words));
print $constWord;
print scalar reverse, " " foreach (@words);
print "\n";

- RASHMI BS June 07, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Modified Perl script

#! /usr/bin/perl
my $str="I am human being";
my @words=split(' ',$str);
my $constWord=join(' ',reverse (@words));
print $constWord;
print"\n";
print scalar reverse, " " foreach (@words);
print"\n";

The out will be displaye as shown below

being human am I
I ma namuh gnieb
~

- RASHMI BS June 07, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

C#

static string Reverse(string input)
        {
            List<string> s = new List<string>();

            s = input.Split(' ').ToList();

            List<string> reversed = new List<string>();

            foreach(var i in s)
            {
                if (String.IsNullOrEmpty(i)) reversed.Add(i);
                else reversed.Add(new string(i.Reverse().ToArray()));
            }

            string returnS = "";

            foreach (var r in reversed)
                returnS += r + " ";

            return returnS.Trim();
        }

- Anonymous April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python solution

sentence = raw_input("Enter String")
sentence = sentence.split()
new_sentence = [word[::-1] for word in sentence]
print ' '.join(str(x) for x in new_sentence)

- Naveen April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In Python

def reverse_loop(word):
  n = len(word) -1
  result = ""
  while(n >= 0):
    result += word[n]
    n-=1
  return result

def revesre_word_in_string(sentence):
  list = sentence.split()
  for i in range(0, len(list)):
    list[i] = reverse_loop(list[i])
  return " ".join(list)

- hankm2004 April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.string;
/**
 * 
 * @author anand
 *
 *Given a string say "I am a human being" the output should reverse all letters of each word
 *but not the whole string as such. Eg: O/p should be "I ma a namuh gnieb" 

 */
public class ReverseWords {

	String result = "";
	public static void main(String[] args) {
	ReverseWords reverse = new ReverseWords();
	String stringToReverse = "I am a human being";
	String reversedString = reverse.completeReversal(stringToReverse);
	System.out.println(reversedString);
	reverse.getResult(reversedString);
	System.out.println(reverse.result);
	}

	private String getResult(String reversedString) {
		if(reversedString.isEmpty()) 
			return "";
		int i = 0;
		StringBuffer word = new StringBuffer();
		while(reversedString != null && reversedString.length() > i && reversedString.charAt(i) != ' ') {
			word.append(reversedString.charAt(i));
			++i;
		}
		if(reversedString.length() == i) {
			result = word.toString() + result;
			return "";
		} else {
			result = ' ' + word.toString() + result;
		}
		return getResult(reversedString.substring(i+1, reversedString.length()));
	}

	private String completeReversal(String stringToReverse) {
		if(stringToReverse.isEmpty()) 
			return "";
		return completeReversal(stringToReverse.substring(1, stringToReverse.length())) + stringToReverse.substring(0, 1);
	}
}

- anandsatheesh2004 April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Quick objective-c version with helper subroutine O(n)
For each word, swaps first and last till it gets to the middle.

- (NSString*)reverseString:(NSString*)input
{
    NSMutableString* operateOn = [NSMutableString stringWithString:input];
    
    NSUInteger firstIdx = 0;
    NSUInteger lastIdx = input.length - 1;
    
    while (firstIdx < lastIdx)
    {
        NSString* first = [NSString stringWithFormat:@"%c", [operateOn characterAtIndex:firstIdx]];
        NSString* last = [NSString stringWithFormat:@"%c", [operateOn characterAtIndex:lastIdx]];
        
        [operateOn replaceCharactersInRange:NSMakeRange(firstIdx, 1) withString:last];
        [operateOn replaceCharactersInRange:NSMakeRange(lastIdx, 1) withString:first];
        
        firstIdx++;
        lastIdx--;
    }
    
    return [NSString stringWithString:operateOn];
}


- (NSString*)reverseWordsOfSentence:(NSString*)sentence
{
    NSMutableString* newSent = [NSMutableString string];
    NSArray* words = [sentence componentsSeparatedByString:@" "];
    for (NSString* word in words)
    {
        [newSent appendFormat:@"%@ ", [self reverseString:word]];
    }
    
    // Remove extra space
    [newSent deleteCharactersInRange:NSMakeRange(newSent.length - 1, 1)];
    
    return [NSString stringWithString:newSent];
}

- valheru April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringCharReverse {
public static void main(String args[]){
String string = "I am a human being";
Stack<Character> myCharStack = new Stack<Character>();
int length = string.length();

for(int i = 0; i < length; i++){
char c = string.charAt(i);
if(c != ' '){
myCharStack.push(c);
} if(c == ' ' || i == length-1){
while (myCharStack.size() != 0){
System.out.print(myCharStack.pop());
}
if(c == ' ')
System.out.print(c);
}
}
}
}

- Java Solution O(n) April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

ruby

str = "I am a human being"
reverse = []

str.split.each do |w|
	reverse << w.reverse
end

puts reverse.join(" ")

- Anonymous April 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

What happened when you wrote that?

- Anon April 14, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

in_arr="I am a human being".split(" ")
flip=""
in_arr.each do |i|
	flip += i.reverse + " "
end
puts flip

reusuable

def flip_words(str=nil)
  in_arr=str.split(" ")
  flip=""
  in_arr.each do |i|
    flip += i.reverse + " "
  end
  puts flip.to_s
end
flip_words("I am a human being")

- E.Santiago January 16, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

static String wordReverse(String input){
String output = "";
String tokens[] = input.split(" ");
for (int i = 0; i < tokens.length; i++) {
StringBuilder s = new StringBuilder(tokens[i]);
output += s.reverse().toString()+" ";
}
return output;
}

- UltiKhopdi April 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

# Ruby

def reverse(sentence)
   arr = sentence.split(' ')
  arr.map!{|w| w.reverse }
  arr.join(' ')
end

- dev April 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

JAVA solutuion
-------------------------------------------------------------------

public void reverse()
	{
		String reverseThis = "I want to pass amazon interview";
		System.out.println(reverseThis);
		String [] words = reverseThis.split("\\s+");
		String reversedString = "";
		for (int i = 0; i< words.length ; i++)
		{
			String tempStr = words[i];
			int length = tempStr.length();
			char [] tempchrArr = new char[length];
			tempchrArr = tempStr.toCharArray();
			char [] tempRevchrArr = new char[length];

			for(int j = 0; j <= length/2;  j++)
			{
				tempRevchrArr[j] = tempchrArr[length-1-j];
				tempRevchrArr[length-1-j] = tempchrArr[j];
			}
			reversedString += String.valueOf(tempRevchrArr) + " ";
		}

		System.out.print(reversedString);

}

- Deepu Thomas April 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C Solution. Handles multiple Spaces.

#include <stdio.h>
#include <stdlib.h>
#define true (0)
#define false (1)
//Assumption: A word ends when an Space is encountered
// No Sanity check( compare to Dictionaty for valid words is done
void reverse(char* input, int length)
{
        int last_pos = length-1;
        for(int i = 0; i < length/2; i++)
        {
                char tmp = input[i];
                input[i] = input[last_pos - i];
                input[last_pos - i] = tmp;
        }

}
int reverseAllWordsInASentence(char arr[])
{
/* Algorithm
	1. Loop through the sentence till end
	2. Keep track of start of word
	3. When End of word is detected( space detected),. mark the end of work
	4. Reverse start to End
	5. Continue till space ends
*/
	int i = 0 ;
	int startWordIndex = 0;
	/* Skip the leading spaces */
	while(arr[i] == ' ')
		i++;
 	startWordIndex = i;
	int EndWordIndex = 0;
	int inAWord = 1;
	//Loop through entire sentence
	for(i = startWordIndex ; arr[i] != '\0'; i++){
		if(arr[i] == ' '){ //Found Space
	 	  if(inAWord == 1){ //Only process if a word is in Progress
		  	EndWordIndex = i-1;
		  	inAWord = 0;
			//Reverse the found word
		  	reverse(&arr[startWordIndex], (EndWordIndex - startWordIndex)+1);
		  }else{// Skip this.. May be continous spaces
			continue;
		  }
		}else{ //Found a Character
		   if(inAWord == 0){ //This is a start of new word
			 startWordIndex = i;
			 inAWord = 1;
		   }else{ //Continue. Word is in progress
			continue;
	           }
		}

	}
	//Reverse the last word
	if(inAWord == 1){
		EndWordIndex = i-1;
		inAWord= 0;
		reverse(&arr[startWordIndex],(EndWordIndex - startWordIndex)+1);
	}
	return true;
}

int main( int argc, char **argv)
{
	if(argc != 2) {
		printf("Usage : %s : <string>\n",argv[0]);
		exit(false);
	}
	char *str =argv[1];
	printf("String is %s\n", str);
	if(reverseAllWordsInASentence(str) == true){
		printf("Reverse is:%s\n",str);
	}
	return true;
}

- Arun Bhakthavalsalam April 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void reverseString(char[] str){
	
int i = 0 ;
int j =0;
int start =0;
while(i< str.length){
	
	char c = str[i];
	System.out.println(c);
	if( c == 32 ||i==str.length-1)
		{
			j=start;
			int k=i;
			if(i==str.length-1)++k;
			while(j<k){
				char temp= str[k-1];
				str[k-1]=str[j];
				str[j]=temp;
				++j;--k;
			}
			start=i+1;
		}
		
		++i; 
	}
		System.out.println(String.valueOf(str));
	}

- Kiran Hiremath April 13, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void reverseWordsInStr(char arr[])
{
	int i =0,j=0,k=0;
	char reverseArr[255];
	char resulArr[255];
	
	while(arr[i]!='\0')
	{
		if(arr[i]!=' ')
		{
			reverseArr[j] = arr[i];
			j++;i++;
			continue;
		}
		while(j)
		{
			resulArr[k]= reverseArr[j-1];
			j--;k++;
			cout << "hi"<<resulArr[k];
		}
		
		resulArr[k] = ' ';
		k++;
		i++;
	}
	while(j)
	{
		resulArr[k]= reverseArr[j-1];
		j--;k++;
		cout << "hi"<<resulArr[k];
	}
	resulArr[k] = '\0';
	
}

- Anonymous April 13, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java Method:

//Assuming stack methods are implemented.

public void reverse ( String test , int length )
{
if(test == NULL) System.out.println("Empty String");

else if (length == 1 ) System.out.println(test)

else

for ( int i = 0 ; i<length ; i++ )
{
char c = test[i];
if (c == " " && stack.top == -1) System.out.println(c);
else if (c == " " && stack.top !=-1)
{ System.out.println( stack.pop());
System.out.println(c);
}
else if (c != " ") stack.push(c);
}
}

- Satish April 13, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <list>
#include <stack>
#include <queue>
#include <string>
using namespace std;
int main()
{
	char inputSentence[100];
	cout<<"Enter any sentence:- \n";	
	cin.getline(inputSentence,100);
	system("cls"); // used to clear the screen, but it is bad practice to call system.... need to figure out some alternative

	if(inputSentence[0] == 0)
		return 0;
	else
		cout<<"You Entered : "<<inputSentence;

	
	list<stack<string>> words;
	queue<stack<char>*> sentence;
	stack<char> * word;
	int i =0;	
	while(inputSentence[i])
	{
		
		word = new stack<char>();

		while(inputSentence[i]  != ' ')
		{
			word->push(inputSentence[i]);	
			if(inputSentence[i+1]!=0)
				i++;
			else
				break;
		}
		i++;
		sentence.push(word);
	}
		
	string reversedSentence="";
	while(!sentence.empty())
	{
		word=sentence.front();
		sentence.pop();

		while(!word->empty())
		{
			reversedSentence +=word->top();
			word->pop();
		}
		delete word;
		reversedSentence.append(" ");		
	}	
	cout<<"\n\n\n The required reversed sentence is \n"<<reversedSentence.c_str();
}

- Arshad Hussain April 14, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

list<stack<string>> words; //Not used --- arshad

- Arshad Hussain April 14, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public ActionResult Index()
        {
            //I am a human being
            List<string> mysentence = new List<string>();
            string sentence = "I am a human being";
            string[] word = sentence.Trim().Split(' ');
            string reverse = string.Empty;
            string forward = string.Empty;
            for (int i = 0; i < word.Length; i++)
            {
                forward = word[i].ToString();
                for (int j = forward.Length-1; j >=0; j--)
                {
                    reverse += forward.Substring(j, 1);
                }
                mysentence.Add(reverse);
                reverse = string.Empty;
            }
            return View();
        }

- Anonymous April 14, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python

def reverse(word):
    return ''.join(list(word)[::-1])

def ReverseWordsInString(givenString):
    print "Original: %s\n" % givenString
    list_of_words = givenString.split()
    new_list_of_words = [reverse(word) for word in list_of_words] 
    return ' '.join(new_list_of_words)

print ReverseWordsInString("I am a human being")

- Rahul Biswas April 15, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringManipulation {
	
	public static void main(String [] args) throws IOException
	{
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		String strToModify=br.readLine();
		String outputString="";
		StringTokenizer st= new StringTokenizer(strToModify);
		Queue<String> queue= new LinkedList<String>();
		while(st.hasMoreTokens())
		{
			queue.add(st.nextToken());
		}
		
		while(!queue.isEmpty())
		{
			String temp= queue.poll();
			if(temp.equals(" "))
			{
				outputString=outputString+temp;
			}
			else{
				if(outputString!="")
				{
					outputString=outputString+" "+reverseString(temp);
				}
				else
				{
					outputString=outputString+reverseString(temp);
				}
			}
		
		}
		System.out.println(outputString);
	}
	
	public static String reverseString(String initialString)
	{
		char [] arrChar= initialString.toCharArray();
		String outString="";
		for(int i=arrChar.length-1; i>=0;i--)
		{
			outString=outString+arrChar[i];
		}
		
		
		
		return outString;
	}

}

- Nik April 15, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ReverseWords {

	public static void main(String[] args) {
		
		String words = "I am a human being";
		String[] array = words.split(" ");
		for(String word : array){
			if(word.isEmpty()){
				System.out.print(" ");
			}else {				
				char[] charArray = word.toCharArray();
				for(int i=charArray.length-1;i>=0;i--){
					System.out.print(charArray[i]);
				}
				System.out.print(" ");
			}
		}
	}
	
}

- Naresh April 15, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

include <unistd.h>
#include <string.h>
#include <stdio.h>
char *reverseString(char *str);
int main (int argc, char *argv[])
{
char line[]="I am a human being";
unsigned short int len = 0;
char *tok = NULL;
tok = strtok(line, " ");
while(tok)
{
printf("%s ", reverseString(tok));
tok = strtok(NULL, " ");
}
printf("\n");
return 0;
}

char *reverseString(char *str)
{
unsigned int len = 0, i = 0;
len = strlen(str);
char c;
for(i = 0; i < (len/2); i++, len--)
{
c = str[i];
str[i] = str[len -1];
str[len -1] = c;
}
return str;
}

- Baijnath Singh April 15, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#!/usr/bin/perl -w
my @words;
$str="I am a human being";
@arr=split(' ',$str);

for ($i=0;$i<$#arr+1;$i++) {

$_=$arr[$i];
# print $_,"\n";
@words = split ('',$_);

for($j=$#words;$j>=0;$j--) {
$_=$words[$j];
print $_;

}
print " ";
}

- Avinash Pani April 15, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>

int main()
{
char *str = "I am an Indian";
char *ptr = str;
int c=0,m=0;
while(1)
{
if(*str == ' ' || *str == '\0')
{
m = c;
ptr--;
while(m)
{
printf("%c",*ptr);
ptr--;
m--;
}
ptr++;
while(c)
{
ptr++;
c--;
}
printf(" ");
}

if (*str == '\0')
break;

c++;
str++;
ptr++;


}
return 0;
}

- Amit Kumar April 15, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

in Perl:
perl -e " print scalar reverse('I am a Human Being');"

output:
gnieb namuH a ma I

- Nsr April 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
using namespace std;

char * split(char ch,char *str=NULL)
{
static char *ptr=str;

while((*ptr)&&(*ptr == ch))ptr++;
char *splitPtr=ptr;

while(*ptr)
{
if(*ptr==ch)
{
*ptr++='\0';
break;
}
else
ptr++;
}

return splitPtr;
}
char * reverse(char *str)
{
int i=0;
while(i<(strlen(str)/2))
{
str[i]=str[i]+str[strlen(str)-1-i];
str[strlen(str)-1-i]=str[i]-str[strlen(str)-1-i];
str[i]=str[i]-str[strlen(str)-1-i];
i++;
}
return str;
}
int main()
{
char str[]="I am a human being";
char *splitStr=NULL;
splitStr=split(' ',str);
while(*splitStr)
{
cout<<reverse(splitStr)<<" ";
splitStr=split(' ');
}

return 0;
}

- Karthik April 22, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <algorithm>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
#include <iostream>
std::string reverse(std::string szSrc) {
    std::stringstream smSrc(szSrc);
    std::ostringstream smDest;
    std::istream_iterator<std::string> beg(smSrc), end;
    std::vector<std::string> src(beg, end);
    for(auto& words: src) {
        std::reverse(words.begin(), words.end());
    }
    std::copy(src.begin(), src.end(), std::ostream_iterator<std::string>(smDest, " "));
    return smDest.str();
}
int main(){
    std::cout<<reverse("I am a human being")<<std::endl;
    return 0;


}

- Abhijit Bhattacharjee April 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
//void revwrdInSent(char arr[]);
void main()
{
//char arr[255]="rohit singh bisht";
char arr[255];
clrscr();
printf("enter a sentense");
gets(arr);
revwrdInSent(arr);
getch();
}
int revwrdInSent(char arr[])
{
int i,j,k;
char revarr[255];
char resarr[255];
i=0;
j=0;
k=0;
while(arr[i]!='\0')
{
if(arr[i]!=32)
{
revarr[j]=arr[i];
j++; //4
i++; //4
continue;
}
while(j) //j=5,i=5
{
//printf("%d",k);
resarr[k]=revarr[j-1];
//printf("%d",k);
j--; //0 //4
printf("%c",resarr[k]);
k++;
}
resarr[k]=32; //5
printf("%c",resarr[k]);
k++; //6
i++; //5
}
while(j)
{
resarr[k]=revarr[j-1];
j--;
printf("%c",resarr[k]);
k++;
}
resarr[k]='\0';
return 0;
}
#include<stdio.h>
//void revwrdInSent(char arr[]);
void main()
{
//char arr[255]="rohit singh bisht";
char arr[255];
clrscr();
printf("enter a sentense");
gets(arr);
revwrdInSent(arr);
getch();
}
int revwrdInSent(char arr[])
{
int i,j,k;
char revarr[255];
char resarr[255];
i=0;
j=0;
k=0;
while(arr[i]!='\0')
{
if(arr[i]!=32)
{
revarr[j]=arr[i];
j++; //4
i++; //4
continue;
}
while(j) //j=5,i=5
{
//printf("%d",k);
resarr[k]=revarr[j-1];
//printf("%d",k);
j--; //0 //4
printf("%c",resarr[k]);
k++;
}
resarr[k]=32; //5
printf("%c",resarr[k]);
k++; //6
i++; //5
}
while(j)
{
resarr[k]=revarr[j-1];
j--;
printf("%c",resarr[k]);
k++;
}
resarr[k]='\0';
return 0;
}

- Rohit Bisht April 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class reverseStringArray {

	public static void main(String[] args) {
	
		String str = "I am a human being";
		String[] splitted = new String[6];
		String[] splits = new String[6];
		int i,j,k;
		String temp = new String();
		try
		{
		splitted = str.split("\\s+");
		
		for(i=0; i<splitted.length; i++)
		{			
			if(splitted[i].length() > 1)
			{
				char[] tArr = splitted[i].toCharArray();
				for(j = tArr.length; j>0; j--)
				{
					temp += tArr[j-1];
				}
				
				//System.out.println(i+"temp->"+temp);
				splits[i] = temp;
				temp = " ";
			}else if(splitted[i].length() == 1)
			{
				String tArr1 = splitted[i];
				
				System.out.println(i+"splitted->"+splitted[i]);
				splits[i] = tArr1;
			}			
		}
		}catch(Exception e)
		{
			System.out.print("Out of bounds! DOH! should have used vectors"); 
		}
		
		for(k=0;k<splits.length-1;k++)
		{
			System.out.println(k+"->"+splits[k]);
		}
	}

}

- nath.alok59 April 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class reverseStringArray {

	public static void main(String[] args) {
	
		String str = "I am a human being";
		String[] splitted = new String[6];
		String[] splits = new String[6];
		int i,j,k;
		String temp = new String();
		try
		{
		splitted = str.split("\\s+");
		
		for(i=0; i<splitted.length; i++)
		{			
			if(splitted[i].length() > 1)
			{
				char[] tArr = splitted[i].toCharArray();
				for(j = tArr.length; j>0; j--)
				{
					temp += tArr[j-1];
				}
				
				//System.out.println(i+"temp->"+temp);
				splits[i] = temp;
				temp = " ";
			}else if(splitted[i].length() == 1)
			{
				String tArr1 = splitted[i];
				
				System.out.println(i+"splitted->"+splitted[i]);
				splits[i] = tArr1;
			}			
		}
		}catch(Exception e)
		{
			System.out.print("Out of bounds! DOH! should have used vectors"); 
		}
		
		for(k=0;k<splits.length-1;k++)
		{
			System.out.println(k+"->"+splits[k]);
		}
	}

}

- nath.alok59 April 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.regex.*;


class Reverse
{
	public static void main(String args[])
	{

		StringBuilder sb=null;
		String input="I am a human being";
		String result="";
		Pattern pat=Pattern.compile("[a-zA-z]+|[ ]+");
		Matcher mat=pat.matcher(input);
		while(mat.find())
		{
			sb=new StringBuilder(mat.group());
			result+=sb.reverse().toString();

		}
		System.out.println(result);
	}
}

- Aman Raj April 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java > StringBuilder

String WordReverse(String string1)
{
	StringBuilder string2 = new StringBuilder(); //output string
	StringBuilder strTemp = new StringBuilder(); //buffer

	isPreLetter = False; // if the previous letter is alphabetical, suppose there is non-alphabetical ahead of the string

	string1.concat(" "); // sovle problem of the daggling last word

	for(int i = 0; i<string1.length(); i++)
	{
		if (int)string[i]>=65  AND string[i]<=122  AND (string[i]<=90 OR string[i]>=97)		//IsAlabet(string[i])
		{
			if isPreLetter //previous alphabetical, current alphabetical 
				strTemp.Append(string1[i]);

			else //previous non-alphabetical, current alphabetical 
				strTemp.Delete();
				strTemp.Append(string1[i]);
				isPreLetter = True;
		}else{
			if isPreLetter //previous alphabetical, current non-alphabetical 
				string2.Append(strTemp.ToString());
				isPreLetter = False;

			else //previous non-alphabetical, current non-alphabetical 
				string2.Append(string1[i]);
		}

	}

	string2.Delete(i); //cut off the last character
	
	return string2.ToString(); //convert from StringBuilder to String

}

- mikezebin April 24, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use regular expression in this -

String arr[] = str.split("\\s+");

for(int i =0; i< arr.length; i++){
String a = arr[i];

if(arr[i].length() > 1){

for(int j = arr[i].length() -1; j >= 0 ; j--){
System.out.print(a.charAt(j));
}
}else{
System.out.println(arr[i]);
}

}

- jassi.srmcem April 27, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

my $input="3 2 1 8 4 2 7 1 8 3 5 7";
my @array=split(' ',$input);
print "@array \n";
@array1=sort {$a <=> $b} @array;
print "@array1 \n";
for (my $i=0; $i< @array1 - 1; $i++){
	if ($array1[$i] == $array1[$i+1]){
		splice(@array1, $i , 1);
	}
}
print "@array1 \n";

- Sammy April 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
 * Created by priganesh on 4/27/14.
 */
public class ReverseString {

    /**
     * recursive function to reverse the string
     * goal is to do this just in O(n)
     * no spliting the string, no usage of any data structures
     * no ready made methods
     * @param input string
     * @param index index to start reading the char
     */
    public void reverse(String input, int index) {
//        System.out.println("Input : "+input+" given index : "+index);
        if(input == null || input.isEmpty()) return;

        StringBuilder sb = new StringBuilder();
        if(index == 0) {
            sb.append(input);
        } else {
            while(index != 0) {
//                System.out.println("Index : "+index);
                if(input.charAt(index) != ' ') {
                    sb.append(input.charAt(index));
                } else {
                    sb.append(' ');
                    if(index > 0) {
//                        System.out.println("string to recurse : "+input.substring(0,index)+" index : "+index);
                        int lastIndex = index-1;
                        reverse(input.substring(0,index),lastIndex);
                    }

                    break;
                }
                if(index == 1) {
                    sb.append(input.charAt(0));
                }
                index--;
            }
        }

        String printStr = sb.toString();
        if(printStr.charAt(printStr.length()-1) == ' ') {
            System.out.print(' ');
            System.out.print(printStr.substring(0,printStr.length()-1));
        } else {
            System.out.print(sb.toString());
        }


    }

    public static void main(String[] args) {
        ReverseString reverseString = new ReverseString();
//        String input = "  Iddly   Vadai Sambar";
//        reverseString.reverse(input,input.length()-1);
//        System.out.println("\n");
        String input = "I am a human being";
        reverseString.reverse(input,input.length()-1);
    }
}

- Gan April 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

python:

def exch(i,j,sentence):
  c = sentence[i]
  sentence[i] = sentence[j]
  sentence[j] = c

def revWord(start,end,sentence):
  while end > start:
    exch(start,end,sentence)
    end -= 1
    start += 1

def revWords(sentence):
  start = 0
  end = len(sentence)
  for i in range(0,end):
    c = sentence[i]
    if (c == ' ') or (i == (end-1)):
      e = i-1 if c == ' ' else i
      revWord(start,e,sentence)
      start = i+1

- foo April 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int reverse(char *,int);
int main()
{
char a[]={"i am ashok kumar bhukhar "};
char *p,*q;
int l,i,counter=0;
l=strlen(a);
p=a;
for(i=0;i<l;i++)
{
if(a[i]==' '||a[i]=='\0')
{
q=p+i-counter;
reverse(q,counter);
counter=0;
}
else
counter++;
}
cout<<"welcome to amazon problem:\n";
cout<<a;
getch();
return 0;
}
int reverse(char *s,int m)
{
char *r;
r=s+m;
char temp;
while(s<r)
{
temp=*s;
*s=*r;
*r=temp;
r--;
s++;
}
return 0;
}

- ashokcsenitj16 May 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.practice.string.operations;

import java.util.Stack;

/*
Given a string say "I am a human being" the output should reverse all letters of each word but not the whole string as such.
Eg: O/p should be "I ma a namuh gnieb"
*/
public class ReverseOfWordsInStatement {

public static void main(String[] args) {
String str = "I am a human being";
System.out.println(reverseOfWords(str));
}

private static String reverseOfWords(String str) {
char[] afterStr = new char[str.length()];
Stack<Character> stack = new Stack<Character>();
int index = 0;

for (char b : str.toCharArray()) {
if (b != ' ') {
stack.push(b);
} else {
while (!stack.isEmpty())
afterStr[index++] = stack.pop().charValue();
afterStr[index++] = ' ';
}
}
while (!stack.isEmpty())
afterStr[index++] = stack.pop().charValue();
return new String(afterStr);
}
}

- Sravanakumar(ARICENT) May 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

$str="God is love";
print "$str\n";
@a=split /\s/,$str;
foreach(0..$#a)
{
$a[$_]= (scalar reverse $a[$_]).' ';
}
print @a;

- sudarson May 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Short and Sweet:

String name= "My name is sameed";
		String [] name_array;
		StringBuffer reversed= new StringBuffer();
		name_array= name.split(" ");
		for (int i = 0; i < name_array.length; i++) {
			for (int j = name_array[i].length()-1; j >=0 ; j--) {
				reversed.append(name_array[i].charAt(j));
			}
			reversed.append(" ");
		}
		System.out.println(reversed);

- Sameed May 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#! /usr/bin/perl

print "Enter the string : ";
$str = <STDIN>;
print  "Original array = $str \n";
map {print rev($_). " ";}(split(' ', $str));


sub rev()
{
my $str = shift;
my $result = "";
while(length($str)!=0)
{
$result.=chop($str);
}
return $result;

- Simple code using map function in In Perl May 04, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#! /usr/bin/perl

print "Enter the string : ";
$str = <STDIN>;
print  "Original array = $str \n";
map {print rev($_). " ";}(split(' ', $str));


sub rev()
{
my $str = shift;
my $result = "";
while(length($str)!=0)
{
$result.=chop($str);
}
return $result;

- Simple code using map function in In Perl May 04, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

s/(\S+)/join('',reverse(split('',$1)))/ge

- perl monk May 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class ReverseString{
	public static void main(String[] args){
		String str = "I am a human being";
		for(String word : str.split(" ")){
			for(int i=(word.length()-1); i>=0; i--){
				System.out.print(o.charAt(i));
			}
			System.out.print(" ");
		}
	}

}

- Utsav Parashar May 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String s1 = "I am a human being";

		StringBuffer bf=new StringBuffer(s1);
		String[] br=bf.reverse().toString().split(" ");
		int n=br.length;
		for(int i=n-1;i>=0;i--){
			System.out.print(br[i]+" ");
		}

- Arun May 08, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String original="I am a human being";
		String reversed="";
		
		StringTokenizer strToken=new StringTokenizer(original);
		
		while(strToken.hasMoreElements())
		{
			StringBuilder word = new StringBuilder((String)strToken.nextElement()).reverse();
			reversed+=word;
			
			if(strToken.hasMoreTokens())
			reversed+=" ";
		}
		
		System.out.println(reversed);

- Asmi May 14, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Below code works though there are extra spaces.

public class ReverseWords {
	
	public static void main(String[] args)
	{
		String toBeReversed = "I am a   human being";
		String[] toBeReveresedArr = toBeReversed.split(" ");
		StringBuilder reversed = new StringBuilder();
		for(int i=0;i<toBeReveresedArr.length;i++)
		{
			reversed.append(" "+(new StringBuffer(toBeReveresedArr[i])).reverse().toString());
		}
		
		System.out.println("Reversed string is"+reversed.toString());
	}

}

- Hari Krishna May 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Thanks Larry@Perl :)

print "Please provide a string of your choice\n\n";
$str=<STDIN>;
@arr=split(' ', $str);


for($i=0; $i<=$#arr; $i++)
{
$_=reverse(@arr[$i]);
push(@final,$_);
@final=join(' ',@final);
}
print "@final\n\n";

- Puneet Agrawal May 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You can do this in one line with Ruby :)

2.0.0-p353 :001 > "this is some input text"
 => input = "this is some input text" 
 => "this is some input text" 
2.0.0-p353 :003 > input.split.map(&:reverse).join(" ")
 => "siht si emos tupni txet"

- Ted Pennings May 20, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C# implementation

private static void ReveseStringWord() {

            List<string> words = new List<string>();
            string strLine = " I     am a human  being";
            int sIndex=0;
            for (int i = 0; i < strLine.Length; i++) {
                if (strLine[i] != ' ' && (i==0?' ' :strLine[i - 1] )== ' ')
                {
                    sIndex = i;
                }
                else if((strLine[i] == ' ' || i==strLine.Length-1)&& (i==0?' ' :strLine[i - 1] )!= ' ') {
                    int eIndex = i == strLine.Length - 1 ? i - sIndex + 1 : i - sIndex;
                    string word = strLine.Substring(sIndex, eIndex);
                    if(!string.IsNullOrEmpty(word)){
                        words.Add(word);
                    }
                }
            }
            foreach (string word in words) {
                string output = string.Empty;
                for (int i = 0; i < word.Length; i++)
                {
                    output += word[word.Length-1-i]; 
                }
                Console.WriteLine(output);
            }
        
        }

- sami May 31, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* String reverse : reverse the words of a string */

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

char * word_rev(char *str)
{
char * tempstr,*wrdrev;
int len,i,j,k=0;
tempstr=(char *)malloc(sizeof(char)*100);
len=strlen(str);
printf("strlen is <%d> \n",len);
printf("\n reversing the string \n");

for(i=0;i<len;i++)
*(tempstr+i)=*(str+len-i-1);

printf("\n string after reverse <%s> \n",tempstr);
wrdrev=(char *)malloc(sizeof(char)*100);

for(i=0;i<len;i++)
{
if((i==0) || (*(tempstr+i)==' '))
{
if(*(tempstr+i)==' ')
{
*(wrdrev+i) = ' ';
i++;
}
for(j=i+1;j<=len;j++)
{
if((j==len) || (*(tempstr+j)==' '))
{

for(k=0;k<(j-i);k++)
{
*(wrdrev+i+k)=*(tempstr+j-k-1);
}
break;
}
}
}
}

printf("\n string after word reverse <%s> \n",wrdrev);
return(wrdrev);

}

void main()
{

int i,j;
char *str,*tempstr;

str=(char *)malloc(sizeof(char)*100);

printf("\n Enter the input string : \n");
gets(str);

printf("\n string before reverse <%s> \n",str);
tempstr=word_rev(str);
printf("\n MAIN before end : string is <%s> \n",tempstr);

}

- kbkunalb June 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//PHP Code
$arr = 'I am a human being";';

$arr = explode(" ", $arr);

for( $i=0;$i<count($arr);$i++ ) {
$res .= " " .strrev($arr[$i]);
}
print($res);

- Abhijeet June 09, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Reverse each words in a sentence which contanis multiple spaces
----------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string s = " I am a C# Developer ";
s = removemultipleSpace(s);
string rev ="";
char[] cArray = new char[s.Length];
string[] sArray = new string[s.Length];
sArray = s.Split(' ');
foreach (string ss in sArray)
rev = rev +" " +reverse(ss);
Console.WriteLine(rev);
Console.Read();
}

public static string removemultipleSpace(string s)
{
s = s.Replace(" ", "[]");
s = s.Replace("][", "");
s = s.Replace("[]", " ");
s = s.Trim();
return s;
}

public static string reverse(string word)
{ char[] cArray = new char[word.Length];
for (int i = 0; i < word.Length; i++)
{
cArray[i] = word[word.Length - 1 - i];
}
return new string(cArray);
}
}
}

- sharath June 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class stringreversse {

public static void main(String []args) {
java.util.StringTokenizer st=new java.util.StringTokenizer("I am a human Being", " ");

java.lang.StringBuffer str=new java.lang.StringBuffer("");
while(st.hasMoreTokens())
{
str.append(new StringBuffer(st.nextToken()).reverse());
str.append(" ");





}
System.out.println(str);

}
}

- Saurabh Ahuja July 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void reverseWords(String input) {
         String reverseStr = "";
         String result = "";
         StringBuilder builder = new StringBuilder(128);
         if(input==null || input.length()==0) {
             return;
         } else {
             String[] words = input.split(" ");
             for(String word : words) {
                 char[] wordCharArray = word.toCharArray();
                 for(int i=wordCharArray.length-1;i>=0;i--){
                     reverseStr +=wordCharArray[i];
                 }
                 builder.append(reverseStr).append(" ");
                 reverseStr = "";
             }
         }
         result = builder.toString();
         System.out.println("Reversed word of String: "+result);

- GodIsGreat July 09, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

my $string="i am human         being";
my @arr=split(' ',$string);

my $newStr="";
for(@arr){
	
	my @arrNew= split('',$_);
	$newStr= $newStr.' '. reverse(@arrNew);
}
print "$newStr";

- Anonymous July 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

my $str="I am a human being";
my @arr=split(' ',$str);

foreach my $str (@arr)
{

my $len = length ($str);
for ( my $i=0; $i<$len; $i++)
{
my $bf0_0 = chop($str);
push (@final, $bf0_0);
}
}

- abhishek August 27, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverse(String str)
	{
		if(str.equals(""))
			return "";
		
		
		String str1 = "";
		String word = "";
		for(int i=0; i < str.length(); i++)
		{
			char c = str.charAt(i);
			if(c == ' ')
			{
				str1 = str1  + word;
				str1 =str1 + " ";
				word = "";
			}
			
			else
				word = c  + word;
			
		}
		
			str1 = str1 + word;
		
		return str1;
	}

- pancholi.swapnil September 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Perl solution - with multiple whitespaces

my @words = split(//,$str);
print "@words \n";

sub swap($$) {
	my ($i,$j) = @_;

	while( $i<$j ) {
		($words[$i],$words[$j]) = ($words[$j],$words[$i]);
		$i++;
		$j--;
	}
}

sub main () {

my $i=0;
print "$#words\n";
while ( $i <= $#words ) {
	print "start while::$words[$i]::$i \n";
	my $j = $i;
	if ( $words[$j] =~ /[a-zA-Z]/ ) {
		print "inside if $words[$j]::$j .. \n";
		while ( $words[$j] =~ /[a-zA-Z]/ && $j <= $#words ) {
			print "inside until $words[$j]::$j..\n";
			$j++;
		}
		swap($i,$j-1);
		$i=$j;
	} elsif ( $words[$i] =~ /\s/) {
		print "inside elsif::$i..\n";
		$i++;
	}
	print "end while \n";
}	

my $str;
foreach my $ele ( @words ) {
	$str = $str."$ele";
	}

print "voila:$str \n";

}


main();

- gourabbaksi September 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's the solution for javascript:

function reverseWords(str) {
    var arr = str.split(' '),
        rev_arr = [];
    
    if(typeof(str) === "string" && str.length > 0) {
        for(var i=0; i< arr.length; i++) {
            rev_arr[i] = arr[i].split("").reverse().join("");
        }
        return rev_arr.join(" ");
    }
    
    
}

alert(reverseWords("I am Human"));

- Jay Mehta October 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#!/usr/bin/perl
my $str = "I am human being";
my @words = split(' ',$str);
foreach(@words)
{
	print scalar reverse," ";
}
print "\n";
print  scalar reverse," " foreach (@words);
print "\n";

- Chaks October 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's a java 8 (lamda) solution

import java.util.Arrays;
import java.util.stream.Stream;

public class ReverseWords {
        public static String reverse(String s) {
                StringBuilder b = new StringBuilder();
                for( int i=s.length() - 1 ; i>=0 ; i--) {
                        b.append(s.charAt(i));
                }
                return b.toString();
        }
        public static void main(String args[]) {
                Stream<String> a = Arrays.stream(args);
                a.forEach(i -> System.out.print(reverse(i)+" "));
                System.out.println();
        }
}
~/progs/java >java ReverseWords "i am a human   being"
gnieb   namuh a ma i

- Anonymous November 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#!/usr/bin/perl;

$line=<STDIN>;
chop($line);
@stringarray=split('\s+', $line);
foreach $word(@stringarray) {
  $revword=scalar reverse $word;
  print $revword;
  print " ";

}

print ("\n");

- sughoshdivanji January 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#!/usr/bin/perl;

$line=<STDIN>;
chop($line);
@stringarray=split('\s+', $line);
foreach $word(@stringarray) {
  $revword=scalar reverse $word;
  print $revword;
  print " ";

}

print ("\n");

- sughoshdivanji January 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

tring str = "I am an Indian";
String[] words = str.split(" ");
StringBuffer outPut = new StringBuffer();
for (int i = 0; i < words.length; i++) {
words[i] = new StringBuffer(words[i]).reverse().toString();
outPut.append(words[i] + " ");
}
System.out.println(outPut.deleteCharAt(outPut.length() - 1));

- Anonymous January 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Solution in Java. Feed back appreciated!.

import java.util.*;
import java.util.regex.*;
import java.lang.*;
import java.io.*;


class RevString
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);
		String input= sc.next();
	
		String revString=splitString(input);
		System.out.println(revString);
	}
	
	public static void splitString(String input)
	{
		String[] splitArray = new String[12];
		try
		{
			splitArray= input.split("\\s+");
		}catch(PatternSyntaxException ex){}
		
		for(String word:splitArray)
		{
			newString="";
			for(int k=word.length()-1; k>=0;k--)
				newString=newString + word.charAt(k);
		    revString=revString+ " " +newString;
		    
		}
		return revString;
	}
}

- Glad Born January 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, keep spaces and punctuation marks as it is only reverse the words in the sentence

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- Anonymous January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, keep spaces and punctuation marks as it is only reverse the words in the sentence

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- viks January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, keep spaces and punctuation marks as it is only reverse the words in the sentence

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- viks January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, keep spaces and punctuation marks as it is only reverse the words in the sentence

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- viks January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, keep spaces and punctuation marks as it is only reverse the words in the sentence

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- viks January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, keep spaces and punctuation marks as it is only reverse the words in the sentence

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- viks January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, keep spaces and punctuation marks as it is only reverse the words in the sentence

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- viks January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, keep spaces and punctuation marks as it is only reverse the words in the sentence

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- viks January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer, keep spaces and punctuation marks as it is only reverse the words in the sentence

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- viks January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Keep the spaces and punctuations as it is. and reverse only words in string

import java.util.Stack;

public class ReverseWodsOfString {
	public static void main(String[] args){
		String input = "I am a human being";
		System.out.println(reverseWordsOfSentence(input));
	}
	
	public static String reverseWordsOfSentence(String input){
	     StringBuilder sb = new StringBuilder();
	     Stack<Character> stack = new Stack<>();
	     for(int i = 0; i<input.length(); i++){
	          if(input.charAt(i) >= 36 && input.charAt(i) <= 255){
	               stack.push(input.charAt(i));
	          }else{
	               while(!stack.isEmpty()){
	                    sb.append(stack.pop());
	               }
	               sb.append(input.charAt(i));
	          }
	     }
	     while(!stack.isEmpty()){
	    	 sb.append(stack.pop());
	     }
	     return sb.toString();
	}
}

- vss1987 January 28, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#!/usr/bin/perl -w

use strict;

my $string = "My Name is Brijesh";
my @array = split(/\s+/,$string);
foreach(@array)
{
	my @temp = split(//, $_);
	for(my $i = $#temp; $i>=0; $i--)
	{
		print $temp[$i];
	}
	print " ";

}

- lochan.brijesh March 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#!/usr/bin/perl
# your code goes here

use strict;
my $str = "I am human being";

my @words = split(" ", $str);
my $a = "";
foreach  (@words) {
	$a .= reverse $_ . " ";	
}
print $a;

- krishnx May 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverseWordsOfSentence(String input){
String[] strArray = input.split("\\s");
String result="";
for(String s : strArray){
if(!s.isEmpty())
result+=new StringBuilder(s).reverse().toString()+" ";
}
return result.trim();
}

- Md Jahirul Islam Bhuiyan May 25, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverseWordsOfSentence(String input){
		String[] strArray = input.split("\\s");
		String result="";
		for(String s : strArray){
			if(!s.isEmpty())
				result+=new StringBuilder(s).reverse().toString()+" ";
		}
		return result.trim();

}

- Md Jahirul Islam Bhuiyan May 25, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my answer

public static String reverseWordsOfSentence(String input){
		String[] strArray = input.split("\\s");
		String result="";
		for(String s : strArray){
			if(!s.isEmpty())
				result+=new StringBuilder(s).reverse().toString()+" ";
		}
		return result.trim();
	}

- Md Jahirul Islam Bhuiyan May 25, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverseWordsOfSentence(String input){
String[] strArray = input.split("\\s");
String result="";
for(String s : strArray){
if(!s.isEmpty())
result+=new StringBuilder(s).reverse().toString()+" ";
}
return result.trim();
}

- palash May 25, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//using a stack
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
void wordreversal(char *str)
{
	int j=0;char revstr[100];
	stack<char> wordstack;
	for(int i=0;i<strlen(str)+1;i++)
	{
		if(str[i]!=' ' && i<strlen(str))
		{
			wordstack.push(str[i]);
			
		}
		else//is a space or \0
		{
			if(!wordstack.empty())
			{
				if(j>0)
				 revstr[j++]=' ';
				
				while(!wordstack.empty())
				{
					revstr[j++]=wordstack.top();
					wordstack.pop();
				}
			}
		}
	}
	revstr[j]='\0';
	cout<<revstr;
}
	
int main() {
	cout<<"hello how are you\n";
	wordreversal("hello     how     are    you");
	return 0;

}

- Suyash May 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#! /usr/bin/perl

$string = "I am writing the code to reverse the each word of an string";
@array = split (' ', $string);

foreach (@array) {
@each_word = split('', $_);
foreach $chr (@each_word){
unshift (@reverse_word, $chr);
}
print @reverse_word;
print " ";
@each_word = ();
@reverse_word = ();
}
print "\n";

- chidambar.k June 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#! /usr/bin/perl

$string = "I am writing the code to reverse the each word of an string";
@array = split (' ', $string);

foreach (@array) {
        @each_word = split('', $_);
        foreach $chr (@each_word){
                unshift (@reverse_word, $chr);
        }
        print @reverse_word;
        print " ";
        @each_word = ();
        @reverse_word = ();
}
print "\n";

}

- chidambar.k June 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#! /usr/bin/perl

$string = "I am writing the code to reverse the each word of an string";
@array = split (' ', $string);

foreach (@array) {
@each_word = split('', $_);
foreach $chr (@each_word){
unshift (@reverse_word, $chr);
}
print @reverse_word;
print " ";
@each_word = ();
@reverse_word = ();
}
print "\n";

- chidambar.k June 05, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is perl code

#!/usr/local/bin/perl

use strict;
use warnings;

my $str = "I am human";
my @words = map {scalar reverse $_} split (/ /,$str);
print "@words";

- Nicks June 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is perl code

#!/usr/local/bin/perl

use strict;
use warnings;

my $str = "I am human";
my @words = map {scalar reverse $_} split (/ /,$str);
print "@words";

- Nicks June 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is perl code

#!/usr/local/bin/perl

use strict;
use warnings;

my $str = "I am human";
my @words = map {scalar reverse $_} split (/ /,$str);
print "@words";

- Nicks June 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
{{{x='I am a human being' {{{=re.split('\s+',x)}}} {{{for i in y:}}} {{{reversed.add(i[::-1])}}} - mjain June 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#!/usr/bin/perl -w

use strict;

my $string = "I am human being";
print $string, "\n";
my @words = split(/\s+/, $string);
foreach(@words)
{
	my @characters = split(//, $_);
	my @reverseChars = reverse(@characters);
	print @reverseChars, " ";
}
print "\n";

- lochan.brijesh July 12, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.ArrayDeque;
import java.util.Deque;
class RevChars{

    public static String reverse(String input){

        System.out.println("Input string is " + input);
        Deque<Character> stack = new ArrayDeque<>();
        String retStr = "";

        if(input == null) return null;

        for(Character x: input.toCharArray()){
            if(x == ' '){
                while(stack.size() != 0)
                    retStr = retStr + stack.pop();
                retStr = retStr + x;
            }
            else{
                stack.push(x);
            }
        }
        while(stack.size() != 0)
            retStr += stack.pop();

        return retStr;
    }
}

- blurred July 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

perl code:

$string=~s/(\w+)/reverse $1/eg;

- HoHo_Perl October 22, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class splitString {

public static void main(String[] args) {
String strNew = "";
String str = "I am a human being";
System.out.println("Original String :"+str);
String[] words = str.split("\\s");

for(String s : words){
//String tempstring = s;
int len = s.length();
char[] cs = new char[len];
strNew = strNew + " ";
for(int i=0; i<s.length(); i++){
cs[i] = s.charAt(len-1);
len--;
strNew = strNew + cs[i];
}
}
System.out.println("Reversed String :"+strNew.trim());
}
}

- Anonymous October 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class splitString {

	public static void main(String[] args) {
		String strNew = "";
		String str = "I am a human being";
		System.out.println("Original String :"+str);
		String[] words = str.split("\\s");
		
		for(String s : words){
			//String tempstring = s;
			int len = s.length();
			char[] cs = new char[len];
			strNew = strNew + " ";
			for(int i=0; i<s.length(); i++){
				cs[i] = s.charAt(len-1);
				len--;
				strNew = strNew + cs[i];
			}
		}
		System.out.println("Reversed String :"+strNew.trim());
        }
}

- Anonymous October 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class splitString {

public static void main(String[] args) {
String strNew = "";
String str = "I am a human being";
System.out.println("Original String :"+str);
String[] words = str.split("\\s");

for(String s : words){
//String tempstring = s;
int len = s.length();
char[] cs = new char[len];
strNew = strNew + " ";
for(int i=0; i<s.length(); i++){
cs[i] = s.charAt(len-1);
len--;
strNew = strNew + cs[i];
}
}
System.out.println("Reversed String :"+strNew.trim());
}
}

- Manan October 23, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public string PrintReverseWords(string input)
        {
            string reverse = string.Empty;

            if(string.IsNullOrWhiteSpace(input))
            {
                return string.Empty;
            }

            for (int i = input.Length - 1; i >= 0; i--)
            {
                reverse = reverse + input[i];
            }

            string reverseSentence = string.Empty;
            string word = string.Empty;

            for(int i= 0; i < reverse.Length; i++)
            {
                if (reverse[i] != ' ')
                {
                    word = word + reverse[i];
                }
                else if(!string.IsNullOrWhiteSpace(word))
                {
                    reverseSentence = word + " " + reverseSentence;
                    word = string.Empty;
                }
            }

            
            reverseSentence = word + " " + reverseSentence;//For the last word

            return reverseSentence;

}

- Sudipta Das November 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public string PrintReverseWords(string input)
        {
            string reverse = string.Empty;

            if(string.IsNullOrWhiteSpace(input))
            {
                return string.Empty;
            }

            for (int i = input.Length - 1; i >= 0; i--)
            {
                reverse = reverse + input[i];
            }

            string reverseSentence = string.Empty;
            string word = string.Empty;

            for(int i= 0; i < reverse.Length; i++)
            {
                if (reverse[i] != ' ')
                {
                    word = word + reverse[i];
                }
                else if(!string.IsNullOrWhiteSpace(word))
                {
                    reverseSentence = word + " " + reverseSentence;
                    word = string.Empty;
                }
            }

            
            reverseSentence = word + " " + reverseSentence;//For the last word

            return reverseSentence;

}

- Sudipta Das November 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public string PrintReverseWords(string input)
        {
            string reverseWord = string.Empty;
            string reverseSentence = string.Empty;

            if(string.IsNullOrWhiteSpace(input))
            {
                return string.Empty;
            }

            for (int i = input.Length - 1; i >= 0; i--)
            {
                if (input[i] != ' ')
                {
                    reverseWord = reverseWord + input[i];
                }
                else if (!string.IsNullOrWhiteSpace(reverseWord))
                {
                    reverseSentence = reverseWord + " " + reverseSentence;
                    reverseWord = string.Empty;
                }
            }

            reverseSentence = reverseWord + " " + reverseSentence;//For the last word

            return reverseSentence;
        }

- Sudipta Das November 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public string PrintReverseWords(string input)
        {
            string reverseWord = string.Empty;
            string reverseSentence = string.Empty;

            if(string.IsNullOrWhiteSpace(input))
            {
                return string.Empty;
            }

            for (int i = input.Length - 1; i >= 0; i--)
            {
                if (input[i] != ' ')
                {
                    reverseWord = reverseWord + input[i];
                }
                else if (!string.IsNullOrWhiteSpace(reverseWord))
                {
                    reverseSentence = reverseWord + " " + reverseSentence;
                    reverseWord = string.Empty;
                }
            }

            reverseSentence = reverseWord + " " + reverseSentence;//For the last word

            return reverseSentence;
        }

- Anonymous November 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public string PrintReverseWords(string input)
        {
            string reverseWord = string.Empty;
            string reverseSentence = string.Empty;

            if(string.IsNullOrWhiteSpace(input))
            {
                return string.Empty;
            }

            for (int i = input.Length - 1; i >= 0; i--)
            {
                if (input[i] != ' ')
                {
                    reverseWord = reverseWord + input[i];
                }
                else if (!string.IsNullOrWhiteSpace(reverseWord))
                {
                    reverseSentence = reverseWord + " " + reverseSentence;
                    reverseWord = string.Empty;
                }
            }

            reverseSentence = reverseWord + " " + reverseSentence;//For the last word

            return reverseSentence;
        }

- Sudipta Das November 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

my @array = split(/ /,"i am a human being");
print scalar reverse($_) foreach @array;

- anushenoy May 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ReverseWords {
public static void main(String[] args) {
String s = "i am a human being";
String a[] = s.split("\\s+");
String a2[]= new String[a.length];
String k ="";
for(int i=0;i<a.length;i++){
for(int j=a[i].length()-1; j>=0;j--){
k += a[i].charAt(j);
a2[i]=k;
}
k=" ";
}
for(int i=0;i<a2.length;i++) {
System.out.print(a2[i]);
}
}
}

- KNSManasa December 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript solution

var str = "reverse string";
	
	function reverseStr(str) {
	  var reversed = "";
	  var len = str.length;
	  var arr = [];
	  for (var i = 1; i <= (len); i++) {  
	    reversed += str[len - i];   
	    if (str[len-i]===" " || i===len){
      arr.unshift(reversed);
	      reversed="";
	    }
    
	  }
	
	  var res = arr.join(" ");
      console.log(res);
	  return res;
      
	}
	
	var strReverse = reverseStr(str);

- ac December 15, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript solution

var str = "reverse string";
	
	function reverseStr(str) {
	  var reversed = "";
	  var len = str.length;
	  var arr = [];
	  for (var i = 1; i <= (len); i++) {  
	    reversed += str[len - i];   
	    if (str[len-i]===" " || i===len){
      arr.unshift(reversed);
	      reversed="";
	    }
    
	  }
	
	  var res = arr.join(" ");
      console.log(res);
	  return res;
      
	}
	
	var strReverse = reverseStr(str);

- ac December 15, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is the perl pgm to do this

my $string = "Hi this is a string";
my @arr = split(/\s+/,$string);

foreach my $word (@arr) {
my $b = reverse $word;
print "$b ";
}

- Nakul July 24, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In python:

a=input("ENter the string to reverse:")
arr=a.split()

def reverse(list1):
    out=[]
    for i in list1:
        a=""
        for j in range(1,(len(i)+1)):
            a+=i[-j]
        out.append(a)
    res=' '.join(out)
    return res
    
reverse(arr)

- jagannathans92 March 01, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

my $str='I          am a     human being';
$str =~ s/(\w+)/reverse $1/ge;
print $str;

- Anonymous May 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

##In Perl
my $str='I          am a     human being';
$str =~ s/(\w+)/reverse $1/ge;
print $str;

- Prajwar007 May 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Arrays;
public class ReverseWordsInStatement {
public static void main(String [] args){
String str="I am Rahul";
String srtArray[]=str.split(" ");
StringBuilder sb= new StringBuilder();
StringBuilder sb1= new StringBuilder();
for(int i=0;i<srtArray.length;i++){
sb.append(srtArray[i]);
sb1.append(sb.reverse().toString()+" ");
sb.setLength(0);
}
System.out.println(sb1.toString());

}
}
//Output-: I ma luhaR

- Rahul Rajendra Gawade May 14, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Arrays;
public class ReverseWordsInStatement {
public static void main(String [] args){
String str="I am Rahul";
String srtArray[]=str.split(" ");
StringBuilder sb= new StringBuilder();
StringBuilder sb1= new StringBuilder();
for(int i=0;i<srtArray.length;i++){
sb.append(srtArray[i]);
sb1.append(sb.reverse().toString()+" ");
sb.setLength(0);
}
System.out.println(sb1.toString());

- Rahul Rajendra Gawade May 14, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More