Java : chop and chomp

Perl have very handy Functions to clean up trailing garbage in Strings …

  • chop : deletes the last character of a string. Useful when you append delimiter in a loop, so that the last addition has to be cleaned up
  • chomp : removes trailing sequence of the same character. if the character/s at the end do not match the specs nothing is deleted. Useful to cleanup new-lines/s at the end. Normally happens when reading from file.

Here are those useful Functions implemented for Java :

public class Main {
  
  public static <ARG> void say(ARG arg) { System.out.println(arg); }

  //removing trailing characters
  public static String chomp(String str, Character repl) {
    int ix = str.length();
    for (int i=ix-1; i >= 0; i-- ){
      if (str.charAt(i) != repl) break;
      ix = i;
    }
    return str.substring(0,ix);
  }
  
  //default case, removing trailing newlines
  public static String chomp(String str) {
    return chomp(str,'\n');
  }  

  //hardcut  
  public static String chop(String str) {
    return str.substring(0,str.length()-1);
  }
  
  public static void main(String[] args) {
    say(chomp("hi...",'.'));
    say(chomp("hello\n\n",'\n'));
    say(chomp("hello\n\n"));
    say(chop("howdy."));
    say(chomp("hi...++",'.'));      
  }
}

------

hi
hello
hello
howdy
hi...++