Source

Girl Develop It San Francisco, Teaching Materials, Exercises: Strings: MixUp

Description

Given two strings s1 and s2 and an integer n, swap the first n characters of s1 and s2 and concatenate the results, separated by a space. If either string is less than or equal to n characters in length, return them unmodified but concatenated, separated by a space.

1
2
'foo', 'bar', 3 ⟹ 'foo bar'
'foobar', 'bazqux', 3 ⟹ 'bazbar fooqux'

My solution

1
2
3
4
5
6
7
8
9
10
public class headswap {

    public static String headswap(String s1, String s2, int n) {
        boolean isShort = s1.length() <= n || s2.length() <= n;
        if (isShort) return s1 + " " + s2;
        return s2.substring(0, n) + s1.substring(n) + " " +
               s1.substring(0, n) + s2.substring(n);
    }

}

Tests

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.junit.*;
import static org.junit.Assert.*;

public class headswapTest {
    headswap x = new headswap();

    @Test
    public void test() {
        assertEquals(x.headswap("foo", "bar", 3), "foo bar");
        assertEquals(x.headswap("foobar", "bazqux", 3), "bazbar fooqux");
    }

}