Reversing a string's logic

In this section, let's see how we can print a string in reverse. This is one of the questions that was asked in the Yahoo interview. Let's create a reversedemo class for our example.

We have a string called Rahul, and we want the output to be luhaR. There is one more concept that we need to be aware of: a palindrome. If you type in a string, such as madam, and we reverse the string, it would just give madam as the output. Such types of strings are called palindromes. One such instance of a palindrome is shown in the following code:

package demopack;

public class reversedemo {

public static void main(String[] args) {

String s = "madam";
String t= "";
for(int i=s.length()-1; i>=0; i--)
{
t= t+ s.charAt(i);
}
System.out.println(t);
}
}

We would start by creating a string, called s, and an empty string, called t. We create this empty string to concatenate each element after the for loop to get the output in the console in the form of a string; otherwise, we may get it something like the following:

m
a
d
a
m

Using the concatenation logic, we can display the output as follows:

madam

This was a simple logic that is used to reverse our string and display it in the form of a string using the empty string logic. We used the charAt method and implemented our reverse string. Once we have our reverse string, we can easily compare it with the original string—in our case, this involves comparing the t string with the s string, and if they both match, then we can print that the given string is a palindrome.

Forget about palindromes. This is the concept of string reversal.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.186.92