Reverse String By Preserving Space Position | Java Coding Interview Question Answers

preview_player
Показать описание
In this video, we demonstrated how to reverse a string by preserving space position.

Input
welcome to cloudtech
Output
hcetduo lc otemoclew

#java
#javainterviewquestions
#javacoding
Рекомендации по теме
Комментарии
Автор

Just iterating from last index to start index using single for loop

vinny
Автор

private static String str) {
String temp = "";
int start = 0, end = str.length() - 1;
while (start < str.length()) {
if (str.charAt(start) == ' ') {
temp = temp + ' ';
start++;
} else {
if (str.charAt(end) != ' ') {
= temp + str.charAt(end);


}
else

}
}
return temp;

}

kalvakolusubhash
Автор

private static String reverseString(String inputStr) {
StringBuilder reversedString = new StringBuilder(inputStr.replaceAll("\s+", "")).reverse();
List<Integer> spaces = new ArrayList<>();
for (int i = 0; i < inputStr.length(); i++) {
if (inputStr.charAt(i) == ' ')
spaces.add(i);
}
for (int i : spaces)
reversedString.insert(i, " ");
return reversedString.toString();
}

TechMan-quwb
Автор

import java.util.*;
public class Main {
public static void main(String[] args) {
String st="my name is Dhanu";
ArrayList al=new ArrayList();

char ch[]=st.toCharArray();
String s="";
int j=ch.length-1;
for(int i=0;i<ch.length;i++)
{
if(ch[i]!=' ')
al.add(ch[i]);

}
int size=al.size();
char ch1[]=new char[size];
for(int i=0;i<ch1.length;i++)
{
char c=(char)al.get(size-1);
ch1[i]=c;
size--;
}
int x=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]!=' ')
{ s=s+ch1[x];
x++;}
else
s=s+" ";
}
System.out.print(s);
}
}

hnudj
Автор

public class ReverseAString {

static void ReverseString(String str){

char[] result=str.toCharArray();
int length= result.length;
//
// System.out.println(result);
for (int i=length-1;i>=0;i--){

System.out.print(result[i]);
}

}

public static void main(String[] args) {
String str;
str="Welcome to JAVA";
ReverseString(str);

}
}

hemmishra
Автор

package com.method;

public class ReverseStringPreserveSpace
{
//I/o- Welcome to Java
//O/p- avaJ ot emocleW
public static void main(String[] args)
{
String str="Welcome to Java";
String[] split = str.split(" ");
String newstr="";
for(int i=split.length-1;i>=0;i--)
{
char[] arr = split[i].toCharArray();
String rev="";
for(int j=arr.length-1;j>=0;j--)
{
rev=rev+arr[j];
}
newstr=newstr+rev+" ";
}


}
}

satishbhutawale