reverse words in a string java code example
Example 1: reverse string java
// Use StringBuilder for non-thread environment, it is faster
String string="whatever";
String reverse = new StringBuilder(string).reverse().toString();
System.out.println(reverse);
Example 2: how to reverse a string in java
public class ReverseString {
public static void main(String[] args) {
String s1 = "neelendra";
for(int i=s1.length()-1;i>=0;i--)
{
System.out.print(s1.charAt(i));
}
}
}
Example 3: 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());
}
Example 4: java string reverse
String rev = new StringBuilder("Your String").reverse().toString();
Example 5: 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();
}
}
Example 6: 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]);
}
}