Skip to content

Instantly share code, notes, and snippets.

Avatar

Robert C. Martin unclebob

View GitHub Profile
View Wrapper.java
public class Wrapper {
public static String wrap(String s, int col) {
if (s.length() <= col)
return s;
int space = (s.substring(0, col).lastIndexOf(' '));
if (space != -1)
return (s.substring(0, space) + "\n" + wrap(s.substring(space+1), col));
else
return (s.substring(0, col) + "\n" + wrap(s.substring(col), col));
}
View WrapperTest.java
@Test
public void wrapAfterWordBoundary() throws Exception {
assertThat(wrap("word word", 6), equalTo("word\nword"));
}
View Wrapper.java
public class Wrapper {
public static String wrap(String s, int col) {
if (s.length() <= col)
return s;
else if (s.charAt(col-1) == ' ')
return (s.substring(0, col-1) + "\n" + wrap(s.substring(col), col));
else
return (s.substring(0, col) + "\n" + wrap(s.substring(col), col));
}
}
View WrapperTest.java
public static class WrapTwoWords {
@Test
public void wrapOnWordBoundary() throws Exception {
assertThat(wrap("word word", 5), equalTo("word\nword"));
}
}
View Wrapper.java
public class Wrapper {
public static String wrap(String s, int col) {
if (s.length() <= col)
return s;
else
return (s.substring(0, col) + "\n" + wrap(s.substring(col), col));
}
}
View WrapperTest.java
@Test
public void splitOneWordManyTimes() throws Exception {
assertThat(wrap("abcdefghij", 3), equalTo("abc\ndef\nghi\nj"));
}
View 1 WrapperTest.java
public static class SplitWordTests {
@Test
public void splitOneWord() throws Exception {
assertThat(wrap("word", 2), equalTo("wo\nrd"));
}
}
View 1 WrapperTest.java
public static class DegenerateTests {
@Test
public void wrap_EmptyString_ShouldBeEmpty() throws Exception {
assertThat(wrap("", 1), equalTo(""));
}
@Test
public void stringShorterThanColDoesNotWrap() throws Exception {
assertThat(wrap("word", 10), equalTo("word"));
}
View Wrapper.java
public class Wrapper {
public static String wrap(String s, int col) {
if (s.length() <= col)
return s;
else {
StringBuilder builder = new StringBuilder();
String[] strings = s.split(" ");
int column = 0;
for (String segment : strings) {
column += segment.length();
View Wrapper.java
public class Wrapper {
public static String wrap(String s, int col) {
if (s.length() <= col)
return s;
else {
int lastSpace = 0;
int space;
while ((space = s.indexOf(" ", lastSpace)) != -1) {
if (space > col) {
s = s.substring(0, lastSpace) + "\n" + s.substring(lastSpace+1);
You can’t perform that action at this time.