Strings utility example

There are various places around leveluplunch that show the power of guava's Strings utility class such as common prefix, common suffix, is string null or empty, left pad a string, repeat a string and right pad string. This example will try to bring it together in one page.

Common prefix

public void common_prefix (){
    
    String phrase1 = "semicircle";
    String phrase2 = "semiconductor";
    
    String prefix = Strings.commonPrefix(phrase1, phrase2); 
    
    assertEquals("semic", prefix);
}

Common suffix

public void common_suffix (){
    
    String phrase1 = "fix";
    String phrase2 = "six";
    
    String suffix = Strings.commonSuffix(phrase1, phrase2); 
    
    assertEquals("ix", suffix);
}

Empty to null

public void empty_to_null () {
    
    String val = Strings.emptyToNull("");
    
    assertNull(val);
}

Is null or empty

public void is_null_or_empty () {
        
    String outputVal = null;
    String stringToCheck = "abc";

    if (!Strings.isNullOrEmpty(stringToCheck)) {
        outputVal = "do some work";
    };

    assertEquals("do some work", outputVal);
}

Null to empty

public void null_to_empty () {
        
    String val = Strings.nullToEmpty(null);
    
    assertEquals("", val);
}

Left pad string

public void left_pad_string () {

    String leftPaddedString = Strings.padStart("levelup", 10, ' ');
    
    assertEquals("   levelup", leftPaddedString);
    assertEquals(10, leftPaddedString.length());
    assertThat(leftPaddedString, startsWith(" "));
}

Right pad string

public void right_pad_string () {

    String rightPaddedString = Strings.padEnd("levelup", 10, ' ');
    
    assertEquals("levelup   ", rightPaddedString);
    assertEquals(10, rightPaddedString.length());
    assertThat(rightPaddedString, endsWith(" "));
}

Repeat string

@Test
public void repeat_String () {
    
    String uppityup = Strings.repeat("up", 3);
    assertEquals("upupup", uppityup);
}