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}