How to print the reverse of the String java is object orientated language
without using any predefined function like reverse()
?
This is the simplest solution:
System.out.print("egaugnal detatneiro tcejbo si avaj");
Here you go:
public static void main (String[] args) {
System.out.println(reverserString("Akshay"));
}
private static String reverserString(String src) {
char[] sArr = src.toCharArray();
char[] dArr = new char[sArr.length];
for(int i=sArr.length; i>0; i--) {
dArr[sArr.length-i] = sArr[i-1];
}
return new String(dArr);
}
First of all: Why reinvent the wheel?
That being said: Loop from the length of the string to 0 and concatenate into another string.
public class MyStack {
private int maxSize;
private char[] stackArray;
private int top;
public MyStack(int s) {
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
MyStack theStack = new MyStack(10);
String s="abcd";
for(int i=0;i<s.length();i++)
theStack.push(s.charAt(i));
for(int i=0;i<s.length();i++)
System.out.println(theStack.pop());
}
What is suprising is that most of the answers are wrong! When Unicode is used. Seems like no one understands that java uses UTF-16 under the hood for Text encoding.
Here is my simple answer.
static String reverseMe(String s) {
StringBuilder sb = new StringBuilder();
int count = s.codePointCount(0,s.length());
for(int i = count - 1; i >= 0; --i)
sb.append(Character.toChars(s.codePointAt(i)));
return sb.toString();
}
How about a simple traverse from the end of the string to the beg:
void printRev(String str) {
for(int i=str.length()-1;i>=0;i--)
System.out.print(str.charAt(i));
}