001package ca.uhn.hl7v2.util; 002 003/** 004 * Various string utility methods 005 */ 006public class StringUtil { 007 008 /** 009 * Counts the number of lines in a string by counting the number of "\n" or 010 * "\r" or "\r\n" sequences which appear in it 011 */ 012 public static int countLines(String theString) { 013 int retVal = 1; 014 015 for (int i = 0; i < theString.length(); i++) { 016 char nextChar = theString.charAt(i); 017 if (i > 0 && nextChar == '\n' && theString.charAt(i - 1) == '\r') { 018 continue; 019 } 020 if (nextChar == '\r' | nextChar == '\n') { 021 retVal++; 022 } 023 } 024 025 return retVal; 026 } 027 028 /** 029 * Removes any line separators (\r ot \n) from the end of a string and 030 * returns that string 031 */ 032 public static String chomp(String theLine) { 033 int i; 034 int start = theLine.length() - 1; 035 for (i = start; i >= 0; i--) { 036 char nextChar = theLine.charAt(i); 037 if (nextChar != '\r' && nextChar != '\n') { 038 break; 039 } 040 } 041 042 if (i == start) { 043 return theLine; 044 } else { 045 return theLine.substring(0, i + 1); 046 } 047 } 048 049 /** 050 * Throws an IllegalArgumentException if the value is an empty string or 051 * null 052 */ 053 public static void validateNotEmpty(String theValue) { 054 if (theValue == null || theValue.length() == 0) { 055 throw new IllegalArgumentException(); 056 } 057 } 058 059 /** 060 * Search within a string and replace one substring with another. Based on 061 * the method within Commons-Lang StringUtils. 062 */ 063 public static String replace(String theString, String theMatch, String theReplacement) { 064 StringBuffer buf = new StringBuffer(theString.length()); 065 int start = 0, end = 0; 066 while ((end = theString.indexOf(theMatch, start)) != -1) { 067 buf.append(theString.substring(start, end)).append(theReplacement); 068 start = end + theMatch.length(); 069 } 070 buf.append(theString.substring(start)); 071 return buf.toString(); 072 } 073 074 public static String[] concatenate(String[] array1, String[] array2) { 075 if (array1 == null) return array2; 076 if (array2 == null) return array1; 077 String[] result = new String[array1.length + array2.length]; 078 System.arraycopy(array1, 0, result, 0, array1.length); 079 System.arraycopy(array2, 0, result, array1.length, array2.length); 080 return result; 081 } 082 083 /** 084 * Returns <code>true</code> if the string is null, or contains no non-whitespace characters 085 */ 086 public static boolean isBlank(String theString) { 087 if (theString == null) { 088 return true; 089 } 090 091 for (int i = 0; i < theString.length(); i++) { 092 if (Character.isWhitespace(theString.charAt(i)) == false) { 093 return false; 094 } 095 } 096 097 return true; 098 } 099 100 /** 101 * Inverse of {@link #isBlank(String)} 102 */ 103 public static boolean isNotBlank(String theString) { 104 return !isBlank(theString); 105 } 106 107}