StrUtil.java

jmud-0.11/src/string/StrUtil.java · 8.6 KB

From the archive jmud-0_11.tgz

Download the archive   « Back to the archive contents

package string;

import java.util.TimeZone;
import java.util.SimpleTimeZone;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.Enumeration;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

import util.file.InvalidFileFormatException;
import string.InvalidFlagException;
import misc.Separators;
import util.bit.Bit;
import util.list.Vector;

public class StrUtil {

  static private final int BrazilStandardTime = -3 * 60 * 60 * 1000;

  static private String DAYS_OF_WEEK[] = {
    "domingo",
    "segunda",
    "terça",
    "quarta",
    "quinta",
    "sexta",
    "sábado"
  };

  static public String centerPad(String str, int width, char c) {
    int len = str.length();
    if (width < len) 
      width = len;

    StringBuffer buf = new StringBuffer(width);
    buf.setLength(width);

    int col = (width - len) >> 1;

    int i = 0;
    for (; i < col; ++i)
      buf.setCharAt(i, c);
    for (int j = 0; j < len; ++i, ++j)
      buf.setCharAt(i, str.charAt(j));
    for (; i < width; ++i)
      buf.setCharAt(i, c);

    return buf.toString();
  }

  static public String centerPad(String str, int width) {
    return centerPad(str, width, ' ');
  }

  static public String rightPad(String str, int width, char c) {
    int len = str.length();
    if (width < len)
      width = len;

    StringBuffer buf = new StringBuffer(width);
    buf.setLength(width);

    int i = 0;
    for (; i < len; ++i)
      buf.setCharAt(i, str.charAt(i));
    for (; i < width; ++i)
      buf.setCharAt(i, c);

    return buf.toString();
  }

  static public String rightPad(String str, int width) {
    return rightPad(str, width, ' ');
  }

  static public String leftPad(String str, int width, char c) {
    int len = str.length();
    if (width < len)
      width = len;
    int pad = width - len;

    StringBuffer buf = new StringBuffer(width);
    buf.setLength(width);

    int i = 0;
    for (; i < pad; ++i)
      buf.setCharAt(i, c);
    for (int j = 0; i < width; ++i, ++j)
      buf.setCharAt(i, str.charAt(j));

    return buf.toString();    
  }

  static public String leftPad(String str, int width) {
    return leftPad(str, width, ' ');
  }

    static public String leftWidth(String str, int width, char c) {
	return str.length() > width ? str.substring(0, width) : leftPad(str, width, c);
    }

    static public String leftWidth(String str, int width) {
	return leftWidth(str, width, ' ');
    }

  static public String formatNumber(int value, int width, char c) {
    String str = String.valueOf(value);
    if (str.length() > width)
      str = str.substring(0, width);
    return leftPad(str, width, c);
  }

  static public String formatNumber(int value, int width) {
    return formatNumber(value, width, ' ');
  }

  static private String[] ids = TimeZone.getAvailableIDs(BrazilStandardTime);
  static private SimpleTimeZone btz = new SimpleTimeZone(BrazilStandardTime, ids[0]);
  static private Calendar calendar = new GregorianCalendar(btz);

  static public String getDate() {
    calendar.setTime(new Date());

    return DAYS_OF_WEEK[calendar.get(Calendar.DAY_OF_WEEK) - 1].substring(0,3) + " " +
      String.valueOf(calendar.get(Calendar.YEAR)).substring(2) + "/" +
      formatNumber(calendar.get(Calendar.MONTH) + 1, 2, '0') + "/" +
      formatNumber(calendar.get(Calendar.DAY_OF_MONTH), 2, '0') + " " +
      formatNumber(calendar.get(Calendar.HOUR_OF_DAY), 2, '0') + ":" +
      formatNumber(calendar.get(Calendar.MINUTE), 2, '0') + ":" +
      formatNumber(calendar.get(Calendar.SECOND), 2, '0');
  }

  static public String replace(String str, String oldStr, String newStr) {
    int oldLen = oldStr.length();
    for (int i = 0; i < str.length(); ++i)
      if (str.regionMatches(i, oldStr, 0, oldLen))
	return str.substring(0, i) + newStr + str.substring(i + oldLen);
    return str;
  }

  static public String readDescription(BufferedReader file) 
    throws InvalidFileFormatException {
      String desc = "";

      try {
	for (; ; ) {
	  if (!file.ready())
	    throw new InvalidFileFormatException();
	  
	  String descLine = file.readLine();
	  if (descLine.startsWith(Separators.EOD))
	    break;
	  
	  desc += ((desc == "") ? descLine : Separators.NL + descLine);
	}
	return desc;
      }
      catch(IOException e) {
	throw new InvalidFileFormatException();
      }
  }

  static public void writeDescription(BufferedWriter writer, String desc) 
    throws IOException {
    writer.write(desc); writer.newLine();
    writer.write(Separators.EOD); writer.newLine();
  }

  static public int parseFlags(String str) throws InvalidFlagException {
    str = str.trim();
    int result = 0;
    for (int i = 0; i < str.length(); ++i) {
      char c = str.charAt(i);
      if (c == '-')
	continue;
      else if (c >= 'a' && c <= 'z') 
	result |= (1 << (c - 'a'));
      else if (c >= 'A' && c <= 'F')
	result |= (1 << (c - 'A' + 26));
      else
	throw new InvalidFlagException();
    }
    return result;
  }

  static public String makeFlags(int flags) {
    String f = "";
    for (int i = 0; i < 32; ++i)
      if ((flags & (1 << i)) != 0)
	if (i < 26)
	  f += (char) (i + 'a');
	else
	  f += (char) (i + 'A' - 26);
    return ((f.length() == 0) ? "-" : f);
  }

    static public String listFlags(int vector, String labels[]) {
	String list = "";

	int i = 0;
	int currFlag = 1;
	for (; i < labels.length; ++i) {
	    if (Bit.isSet(vector, currFlag)) {
		list += labels[i++];
		currFlag <<= 1;
		break;
	    }
	    currFlag <<= 1;
	}	
	for (; i < labels.length; ++i) {
	    if (Bit.isSet(vector, currFlag))
		list += ", " + labels[i];
	    currFlag <<= 1;
	}

	return list;
    }

    static public String wrapList(String list, String none) {
	return list.length() == 0 ? none : list;
    }

    static public String niceListFlags(int vector, String labels[], String none) {
	return wrapList(listFlags(vector, labels), none);
    }

    static public String strTable(int ind, String table[]) {
	return (ind >= 0 && ind < table.length) ? table[ind] : "*ERRO*";
    }

    static public String loadAliases(BufferedReader reader) throws IOException {
	return reader.readLine().toLowerCase();
    }

    static public boolean findAlias(String alias, StringTokenizer tok) {
	while (tok.hasMoreTokens()) 
	    if (tok.nextToken().startsWith(alias.toLowerCase()))
		return true;
	return false;
    }

    static public boolean findAlias(String alias, String aliasList) {
	StringTokenizer aliases = new StringTokenizer(alias);
	while (aliases.hasMoreTokens())
	    if (!findAlias(aliases.nextToken(), new StringTokenizer(aliasList)))
		return false;
	return true;
    }

  static public boolean isSpc(char c) {
    return (c == ' ' || c == '\t');
  }

  static public int findSpc(String str, int i) {
    for (; i < str.length(); ++i) {
      char c = str.charAt(i);
      if (isSpc(c))
	break;
    }
    return i;
  }

  static public int skipSpc(String str, int i) {
    for (; i < str.length(); ++i) {
      char c = str.charAt(i);
      if (!isSpc(c))
	break;
    }
    return i;
  }

  static public int nextWord(String str, int i) {
    return skipSpc(str, findSpc(str, i));
  }

  static public String eatFirstWord(String str) {
    return str.substring(nextWord(str, skipSpc(str, 0)));
  }

    static public String eatWords(String str, int n) {
	while (n-- > 0)
	    str = eatFirstWord(str);
	return str;
    }

    static public char getArticle(boolean female) {
	return female ? 'a' : 'o';
    }

    static public String adjustSex(String str, boolean female, char ch) {

	int len = str.length();
	StringBuffer buf = new StringBuffer(len);
	buf.setLength(len);

	for (int i = 0; i < len; ++i) {
	    char c = str.charAt(i);
	    buf.setCharAt(i, c == ch ? getArticle(female) : c);
	}

	return buf.toString();
    }

    static public String adjustSex(String str, boolean female) {
	return adjustSex(str, female, '*');
    }

    static public String listVector(Vector vec, String sep, String none) {
	Enumeration enum = vec.elements();
	
	if (!enum.hasMoreElements())
	    return none;
	
	String str = enum.nextElement().toString();
	
	while (enum.hasMoreElements())
	    str += sep + enum.nextElement().toString();
	
	return str;
    }

    static public StrPair parseQuoted(String str) {
	boolean ok = true;
	int i = 0; 
	int j = 0;
	int len = str.length();
	StringBuffer buf = new StringBuffer(len);
	buf.setLength(len);
	for ( ; i < len; ++i) {
	    char c = str.charAt(i);
	    if (c == '\'') {
		ok = !ok;
	    }
	    else {
		if (isSpc(c) && ok)
		    break;
		buf.setCharAt(j, c);
		++j;
	    }
	}
	buf.setLength(j);
	return new StrPair(buf.toString(), (i < len) ? str.substring(i+1) : "");
    }
}

Site Stats

Snippets: 1791
Codebases: 571