Reverse a String

Palistha
2 min readApr 29, 2022

--

Suppose we have a following string:

let str = “Spiderman”;

Now, we have to reverse the string and get

revstr = “namredipS

So, what are the steps we can take to achieve our goal?

The answer is simple and can be different.

How ever here’s an approach:

  1. Loop through the String Spiderman from n to S. Which means from str.length — 1to 0.

2. Then push the elements to an array one by one.

// loop through array backwardsfor(let i = str.length — 1; i >=0; i — ) {// store elements of str in revstr from behindrevstr.push(str[i])}

3. Now, we just have to convert the array to String.

revstr.join(‘’)

The join()method returns an array as a string. The parameter we pass is the separator. '’ just means there is no separator.

Here’s a complete code:

Reverse a String in Java

To reverse a String in Java is a little different.

  1. We will reverse the same string
String str = “Spiderman”;

2. Now, to loop over the string we must convert it to a char array,

char strToChar[] = str.toCharArray();

The toCharArray()method converts the string to a character array.

3. Now to hold the reversed array, we will create a string

String revstr = “”;

4. After that, we will loop through the character array backwards, we just created.

for (int i = str.length()-1; i >= 0; i - -)

5. Inside the loop, we will concatenate the character with with the String revstr.

revstr = revstr + strToChar[i];

In the first loop, n is concatenated with revstr, then a is concatenated, then m, and so on.

6. Then, we finally print the array

System.out.println(revstr);

Finally, the complete code:

class Main {  public static void main(String[] args) {    // string to reverse
String str = "Spiderman";
// convert string to char array so that you can loop through it
char strToChar[] = str.toCharArray();
// string to hold the reversed array
String revstr = "";
// loop through the char array backwards
for (int i = str.length() - 1; i >= 0; i--) {
// concat the chars to the revstr
revstr = revstr + strToChar[i];
}
// print the revesred String
System.out.println(revstr);
}
}

--

--

Palistha
Palistha

Written by Palistha

Learning and Sharing Everyday

No responses yet