Following example shows how to reverse a String after taking it from command line argument .The program buffers the input String using StringBuffer(String string) method, reverse the buffer and then converts the buffer into a String with the help of toString() method.
public class StringReverseExample{
public static void main(String[] args) {
String string = "abcdef";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}
Result
The above code sample will produce the following result.
String before reverse:abcdef
String after reverse:fedcba
Example
Following another example shows how to reverse a String after taking it from command line argument
import java.io.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
String input = "tutorialspoint";
char[] try1 = input.toCharArray();
for (int i = try1.length-1;i>=0;i--) System.out.print(try1[i]);
}
}
The above code sample will produce the following result.
tniopslairotut
Showing posts with label Reverse. Show all posts
Showing posts with label Reverse. Show all posts
C program to reverse a number
This program reverse the number entered by the user and then prints the reversed number on the screen. For example if user enter 123 as input then 321 is printed as output. In the program we use modulus(%) operator to obtain the digits of a number. To invert number look at it and write it from opposite direction or the output of code is a number obtained by writing original number from right to left. To reverse or invert large numbers use long data type or long long data type if your compiler supports it, if you still have large numbers then use strings or other data structure.
C programming code
#includeint main() { int n, reverse = 0; printf("Enter a number to reverse\n"); scanf("%d",&n); while (n != 0) { reverse = reverse * 10; reverse = reverse + n%10; n = n/10; } printf("Reverse of entered number is = %d\n", reverse); return 0; }
Subscribe to:
Posts (Atom)