public class StringReverseExample{
public static void main(String[] args) {
String string = "abcdef";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("
String before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}
// Not the best way i know but i wanted to challenge myself to do it this way so :)
public static String reverse(String str) {
char[] oldCharArray = str.toCharArray();
char[] newCharArray= new char[oldCharArray.length];
int currentChar = oldCharArray.length-1;
for (char c : oldCharArray) {
newCharArray[currentChar] = c;
currentChar--;
}
return new String(newCharArray);
}
public class ReverseStringByFavTutor
{
public static void main(String[] args) {
String stringExample = "FavTutor";
System.out.println("Original string: "+stringExample);
// Declaring a StringBuilder and converting string to StringBuilder
StringBuilder reverseString = new StringBuilder(stringExample);
reverseString.reverse(); // Reversing the StringBuilder
// Converting StringBuilder to String
String result = reverseString.toString();
System.out.println("Reversed string: "+result); // Printing the reversed String
}
}
// java program to reverse a word
import java.io.*;
import java.util.Scanner;
class GFG {
public static void main (String[] args) {
String str= "Geeks", nstr="";
char ch;
System.out.print("Original word: ");
System.out.println("Geeks"); //Example word
for (int i=0; i<str.length(); i++)
{
ch= str.charAt(i); //extracts each character
nstr= ch+nstr; //adds each character in front of the existing string
}
System.out.println("Reversed word: "+ nstr);
}
}
//Contributed by Tiyasa
// Java Program to reverse a String
// without using inbuilt String function
import java.util.regex.Pattern;
public class Exp {
// Method to reverse words of a String
static String reverseWords(String str)
{
// Specifying the pattern to be searched
Pattern pattern = Pattern.compile("s");
// splitting String str with a pattern
// (i.e )splitting the string whenever their
// is whitespace and store in temp array.
String[] temp = pattern.split(str);
String result = "";
// Iterate over the temp array and store
// the string in reverse order.
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
// Driver methods to test above method
public static void main(String[] args)
{
String s1 = "Welcome to geeksforgeeks";
System.out.println(reverseWords(s1));
String s2 = "I love Java Programming";
System.out.println(reverseWords(s2));
}
}