This is a slight modification to the previous program. Here we should maintain the space as well. For doing that, I am simultaneously tracking the spaces and the words. I have made an assumption that there wont be any trailing or leading spaces in the sentence as such. Even if its there, a slight tweak of the following code would give me the output i desire.
package dsa.stringmanipulation;
import java.util.ArrayList;
import java.util.List;
public class RevWordWhiteSpace {
public static final String SPACE = " ";
private List<Integer> spaceTracker = new ArrayList<Integer>();
private List<String> wordTracker = new ArrayList<String>();
public static void main(String args[]){
RevWordWhiteSpace rev = new RevWordWhiteSpace();
System.out.println(rev.getRevWithWhiteSpace("This should maintain the space in place"));
}
/*
* Lets assume that our input text will not have any spaces before and after
*/
public String getRevWithWhiteSpace(String inputText){
if(inputText!=null && inputText.length()>0){
int lenOfText = inputText.length();
if(lenOfText==1){
return inputText;
}else{
constructLists(inputText);
StringBuilder output = new StringBuilder();
for(int i=wordTracker.size()-1,j=0; i>0; i--,j++){
output.append(wordTracker.get(i));
output.append(constructSpace(spaceTracker.get(j)));
}
output.append(wordTracker.get(0));
return output.toString();
}
}else{
System.out.println("Invalid Sentence");
return null;
}
}
private CharSequence constructSpace(Integer integer) {
String op="";
for(int i=0;i<integer;i++){
op+=" ";
}
return op;
}
private void constructLists(String inputText) {
int tempBufSpace = 0;
String bufWord = "";
for(int i=0;i<inputText.length();i++){
if(inputText.charAt(i)!=' '){
if(tempBufSpace>0){
spaceTracker.add(tempBufSpace);
tempBufSpace=0;
}
bufWord+=inputText.charAt(i);
}else{
if(bufWord.length()>0){
wordTracker.add(bufWord);
bufWord = "";
}
tempBufSpace++;
}
}
if(bufWord.length()>0){
wordTracker.add(bufWord);
}
}
}
//The output produced would be
//place in space the maintain should This
Also code in C++,
#include <iostream>
#include <string.h>
using namespace std;
void str_rev(char s[], int start, int end)
{
int len = end - start;
for(int i=0;i<len/2;i++)
{
char t = s[i+start];
s[i+start] = s[end-i-1];
s[end-i-1] = t;
}
}
int main()
{
char a[] = "my name is prabhu";
cout << "[" << a << "] ==> ";
str_rev(a,0,strlen(a));
cout << "[" << a << "] ==> ";
int start_index = 0;
for(size_t i=0;i<=strlen(a);i++)
{
if(a[i] == ' ' || a[i] == '\0')
{
str_rev(a,start_index,i);
start_index = i+1;
}
}
cout << "[" << a << "] ==> ";
char b[strlen(a)+1];
int i=0, k=0, j=strlen(a)-1;
while(a[i] != '\0')
{
if(a[i] != ' ')
b[k++] = a[i];
else
{
while(a[j] != ' ' && j>=0)
j--;
while(a[j--] == ' ' && j>=0)
b[k++] = ' ';
}
i++;
}
b[k] = '\0';
cout << "[" << b << "]" << endl;
return 0;
}
Cheers,
Bragaadeesh.