Answers for "reverse words in a string in java"

2

Reverse a string in java word by word

// Reverse a string in java word by word
import java.util.Scanner;
public class ReverseStringWordByWord 
{
   public static void main(String[] args) 
   {
      String strWord = "";
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string: ");
      String strGiven = sc.nextLine();     
      char[] chArray = strGiven.toCharArray();
      System.out.println("Reversed string word by word: ");
      for(int a = 0; a < (chArray.length); a++)
      {
         if(chArray[a] != ' ')
         {
            strWord = strWord + chArray[a];
         }
         else
         {
            for(int b = strWord.length(); b > 0; b--)
            {
               System.out.println(strWord.charAt(b - 1));       
            }
            System.out.print(" ");
            strWord = "";
         }
      }
      for(int b = strWord.length(); b > 0; b--)
      {
         System.out.println(strWord.charAt(b - 1));       
      }
      sc.close();
   }
}
Posted by: Guest on February-19-2021
7

string reverse in java

String str = "Hello";
String reverse(String str){
  StringBuilder sb = new StringBuilder();
  sb.append(str);
  sb.reverse();
  return sb.toString();
}
Posted by: Guest on May-09-2020
1

Reverse a string in java

// reverse a string using character array
class ReverseUsingCharacterArray
{
   public static void main(String[] args)
   {
      String str = "HelloWorldJava";
      char[] ch = str.toCharArray();
      for(int a = ch.length - 1; a >= 0; a--)
         System.out.print(ch[a]);
   }
}
Posted by: Guest on December-07-2020
1

reverse a string in java

Solution 1 

public static String StrReverse(String str) {

String reverse="";

for(int i=str.length()-1; i >= 0; i--)

reverse += str.toCharArray()[i];

 

return  reverse;

}

 

Solution 2 (using string buffer)

public  static String  Reverse(String str) {

return new StringBuffer(str).reverse().toString());

}
Posted by: Guest on November-30-2020

Code answers related to "reverse words in a string in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language