Answers for "reverse java string word"

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
2

java string reverse

String str = "Reverse this strings";
//for loop
for (int i = str.length() - 1; i >= 0; i--) {
	System.out.print(str.charAt(i));
}

// StringBuffer for multi thread
StringBuffer sb = new StringBuffer(); 
sb.append(str);
System.out.print(sb.reverse().toString());

// StringBuffer for single thread
StringBuilder sb = new StringBuilder(); 
sb.append(str);
System.out.print(sb.reverse().toString());
Posted by: Guest on June-01-2020

Code answers related to "reverse java string word"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language