Here is a suggestion:
write a method that reverses a string:
Copyprivate static String reverse(String s) { ... }then in your main method, call it when necessary:
Copyif (str.length() >= 5) str = reverse(str);you then need to put the words back together, presumably into the
reversedSentencestring:CopyreversedSentence += str + " "; //you will have an extra space at the end
Side notes:
- using a
StringBuildermay prove more efficient than string concatenation for longer sentences. - you could put all the words back into a
List<String>within the loop and callreversedSentence = String.join(" ", list)after the loop - reversing a string can be done in one line - you should find numerous related Q&As on stackoverflow.
Videos
Here is a suggestion:
write a method that reverses a string:
Copyprivate static String reverse(String s) { ... }then in your main method, call it when necessary:
Copyif (str.length() >= 5) str = reverse(str);you then need to put the words back together, presumably into the
reversedSentencestring:CopyreversedSentence += str + " "; //you will have an extra space at the end
Side notes:
- using a
StringBuildermay prove more efficient than string concatenation for longer sentences. - you could put all the words back into a
List<String>within the loop and callreversedSentence = String.join(" ", list)after the loop - reversing a string can be done in one line - you should find numerous related Q&As on stackoverflow.
You can use StringBuilder
Copypublic static String spinWords(String sentence) {
String[] splitWords = sentence.split(" ");
StringBuilder builder = new StringBuilder();
for (String str : splitWords) {
if (str.length() < 5) {
builder.append(str);
else
builder.append(new StringBuilder(str).reverse().toString());
builder.append(" ");
}
return builder.toString().trim();
}
String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = StringUtils.join(reversedWords, " ");
(using ArrayUtils and StringUtils from commons-lang, but these are easy methods to write - just a few loops)
You split the string by the space then iterate over it backwards to assemble the reversed sentence.
String[] words = "This is interview question".split(" ");
String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
rev += words[i] + " ";
}
// rev = "question interview is This "
// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
revb.append(words[i]);
revb.append(" ");
}
// revb.toString() = "question interview is This "
Edit after questions.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main( String[] args ) {
final String welcome = "How should we get words in string form a List?";
final List< String > words = Arrays.asList( welcome.split( "\\s" ));
Collections.reverse( words );
final String rev = words.stream().collect( Collectors.joining( ", " ));
System.out.println( "Your sentence, reversed: " + rev );
}
}
Execution:
Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How
I did suggest first reverse the whole string. Then reverse the substring between two spaces.
public class ReverseByWord {
public static String reversePart (String in){
// Reverses the complete string
String reversed = "";
for (int i=0; i<in.length(); i++){
reversed=in.charAt(i)+reversed;
}
return reversed;
}
public static String reverseByWord (String in){
// First reverses the complete string
// "I am going there" becomes "ereht gniog ma I"
// After that we just need to reverse each word.
String reversed = reversePart(in);
String word_reversal="";
int last_space=-1;
int j=0;
while (j<in.length()){
if (reversed.charAt(j)==' '){
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
word_reversal=word_reversal+" ";
last_space=j;
}
j++;
}
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
return word_reversal;
}
public static void main(String[] args) {
// TODO code application logic here
System.out.println(reverseByWord("I am going there"));
}
}
First of all, there is a better way to reverse the words. But lets look at your program.
I want my program to output each word on a new line.
If you want to print each word in a new line, you could either add each word to a list of words and print each word in a new line or you could just add "\n" at the end of each word.
Also notice how the letter "n" is missing from curtain and there is no space between the last two words.
This is because the endIndex starts at sentence.length()-1 and substring in Java works by extracting from startIndex to endIndex - 1 i.e. endIndex is exclusive and startIndex is inclusive.
You can fix it by declaring endIndex = sentence.length() and iterate from i = sentence.length()-1 to 0.
With that the code would be:
public static void main(String[] args) {
String sentence = new String("pay no attention to that man behind the curtain");
String reversed = "";
int endIndex = sentence.length();
for(int i = sentence.length()-1; i >= 0; i--) {
if(sentence.charAt(i) == ' ') {
reversed += sentence.substring(i+1, endIndex) + "\n";
endIndex = i;
}
}
reversed += sentence.substring(0, endIndex);
System.out.println(reversed);
}
The better way is :
a) Convert your string to character array
b) Then reverse the whole character array which would become :
niatruc eht dniheb nam taht ot noitnetta on yap
c) Then reverse the letters between each space in-place.
d) You will get back the new character array that represents:
curtain the behind man that to attention no pay
and you can construct a string from the new character array.
Try this code out:
import java.util.Scanner;
public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");
Scanner read = new Scanner(System.in);
String str = read.nextLine();
String reverse = "";
for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}
System.out.println("Reversed string is:");
System.out.println(reverse);
}
}