Avatar of w1zeman1p

w1zeman1p's solution

to Reverse String in the Java Track

Published at Mar 04 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Reverse a string

For example: input: "cool" output: "looc"

Java Tips

For more help on how to solve this exercise, please refer to the tutorial provided as part of the hello world exercise: TUTORIAL.md

Running the tests

You can run all the tests for an exercise by entering

$ gradle test

in your terminal.

Source

Introductory challenge to reverse an input string https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

ReverseStringTest.java

import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class ReverseStringTest {

    @Test
    public void testAnEmptyString() {
        assertEquals("", new ReverseString().reverse(""));
    }

    @Ignore("Remove to run test")
    @Test
    public void testAWord() {
        assertEquals("tobor", new ReverseString().reverse("robot"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testACapitalizedWord() {
        assertEquals("nemaR", new ReverseString().reverse("Ramen"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testASentenceWithPunctuation() {
        assertEquals("!yrgnuh m'I", new ReverseString().reverse("I'm hungry!"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testAPalindrome() {
        assertEquals("racecar", new ReverseString().reverse("racecar"));
    }

}
class ReverseString {

    String reverse(String inputString) {
      if(inputString.length() == 0) {
        return "";
      }

      String outputString = new String(inputString);
      String reversed = reverse(inputString.substring(1, inputString.length()));
      return reversed + inputString.substring(0, 1);
    }

}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?