Reverse a String with Space

package org.wesome.dsalgo;

public class ReverseString {
    static String reverse(String string) {
        if (string.isEmpty()) {
            throw new RuntimeException("Invalid String");
        }
        String[] strings = string.split(" ");
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : strings) {
            char[] chars = s.toCharArray();
            char temp;
            for (int i = 0; i < chars.length / 2; i++) {
                temp = chars[i];
                chars[i] = chars[chars.length - 1 - i];
                chars[chars.length - 1 - i] = temp;
            }
            stringBuilder.append(new String(chars)).append(" ");
        }
        return stringBuilder.toString().trim();
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class ReverseStringTest {

    @Test
    void reverseStringTest1() {
        String reverse = ReverseString.reverse("abcba");
        Assertions.assertEquals("abcba", reverse);
    }

    @Test
    void reverseStringTest2() {
        String reverse = ReverseString.reverse("i am learning ds algo from wesome.org");
        Assertions.assertEquals("i ma gninrael sd ogla morf gro.emosew", reverse);
    }

    @Test
    void reverseStringTest3() {
        String reverse = ReverseString.reverse("madam");
        Assertions.assertEquals("madam", reverse);
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}

test {
    useJUnitPlatform()
}

 

follow us on