Java tutorial
/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; public class Strings { private static final MessageDigest MESSAGE_DIGEST; public static final String[] EMPTY_ARRAY = new String[0]; static { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException err) { throw new IllegalStateException(); } MESSAGE_DIGEST = md; } public static boolean isBlank(String text) { return text == null || "".equals(text); } public static int countLines(String text) { int startIdx = 0; int lineCount = 1; for (;;) { int lbIdx = text.indexOf('\n', startIdx); if (lbIdx == -1) { break; } lineCount++; startIdx = lbIdx + 1; } return lineCount; } public static boolean isJavaIdentifier(String id) { if (id == null) { return false; } int len = id.length(); if (len == 0) { return false; } if (!Character.isJavaIdentifierStart(id.charAt(0))) { return false; } for (int i = 1; i < len; i++) { if (!Character.isJavaIdentifierPart(id.charAt(i))) { return false; } } return true; } public static String getJavaStringLiteral(String text) { StringBuffer buf = new StringBuffer(); buf.append('"'); int len = text.length(); for (int i = 0; i < len; i++) { char ch = text.charAt(i); switch (ch) { case '\\': buf.append("\\\\"); break; case '\n': buf.append("\\n"); break; case '\r': buf.append("\\r"); break; case '\t': buf.append("\\t"); break; case '"': buf.append("\\\""); break; default: buf.append(ch); break; } } buf.append('"'); return buf.toString(); } public static String getJavaIdentifier(String candidateID) { int len = candidateID.length(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < len; i++) { char ch = candidateID.charAt(i); boolean good = i == 0 ? Character.isJavaIdentifierStart(ch) : Character.isJavaIdentifierPart(ch); if (good) { buf.append(ch); } else { buf.append('_'); } } return buf.toString(); } }