Amazon Interview Question
Testing / Quality AssurancesCountry: India
Interview Type: In-Person
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);
}
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);
}
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)
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());
}
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. :)
:) 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 .
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.
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";
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();
}
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);
}
}
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];
}
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);
}
}
}
}
ruby
str = "I am a human being"
reverse = []
str.split.each do |w|
reverse << w.reverse
end
puts reverse.join(" ")
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);
}
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;
}
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));
}
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';
}
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);
}
}
#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();
}
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();
}
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")
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;
}
}
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(" ");
}
}
}
}
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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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]);
}
}
}
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]);
}
}
}
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);
}
}
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
}
/**
* 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);
}
}
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
#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;
}
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);
}
}
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);
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);
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());
}
}
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);
}
}
/* 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);
}
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);
}
}
}
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);
}
}
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);
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;
}
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();
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"));
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
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));
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;
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
//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;
}
#! /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";
#! /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";
}
#! /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";
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;
}
}
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());
}
}
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());
}
}
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());
}
}
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;
}
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;
}
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;
}
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;
}
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;
}
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]);
}
}
}
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);
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);
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
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());
private static String reverseCharacterInAString(String inputValue) {
String tempStringVal[] = inputValue.split(" ");
char[] stringToChar;
String revesedString = "";
for (int i = 0; i <= tempStringVal.length - 1; i++) {
if (tempStringVal[i].toCharArray().length > 1) {
stringToChar = tempStringVal[i].toCharArray();
for (int j = stringToChar.length - 1; j >= 0; j--) {
revesedString += stringToChar[j];
}
} else {
revesedString += tempStringVal[i];
}
revesedString += " ";
}
System.out.println(revesedString);
return revesedString;
}
Java solution. O(n).
- akashgupta April 11, 2014