package org.apache.commons.lang;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * 文字のセットを処理する多くのルーチン。
 * {@primary Numerous routines to manipulate a character set.}
 *
 * @author <a href="bayard@generationjava.com">Henri Yandell</a>
 * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a>
 * @translator 日置 聡
 * @status firstdraft
 * @update 2003/08/11
 * @version $Id: CharSetUtils.java,v 1.1.1.1 2004/02/13 10:02:04 hioki Exp $
 */
public class CharSetUtils {

    /**
     * CharSetUtils のインスタンスは一般的なプログラムからは生成すべきではありません。
     * 代わりに <code>CharSetUtils.evaluateSet(null);</code> というように使用すべきです。 
     * このコンストラクタは、処理のために JavaBean インスタンスを必要とするツールのために
     * public になっています。
     * {@primary CharSetUtils instances should NOT be constructed in standard programming.
     * Instead, the class should be used as <code>CharSetUtils.evaluateSet(null);</code>.
     * This constructor is public to permit tools that require a JavaBean instance
     * to operate.}
     */
    public CharSetUtils() {
    }

    /**
     * 以下の文法に従って文字のセットを取り扱う CharSetUtil のオブジェクトを生成します。
     *
     * "aeio" の記述は 'a','e',.. を含める事を意味します。
     * "^e" の記述は e 以外を含める事を意味します。
     * しかしこれは指定された文字を否定するだけで、セットのサイズを大きくすることはありません。
     * "ej-m" の記述は e と j から m までを含める(e,j,k,l,m)を意味します。
     *
     * {@primary Creates a CharSetUtils object which allows a certain amount of 
     * set logic to be performed upon the following syntax:
     *
     * "aeio" which implies 'a','e',..
     * "^e" implies not e. However it only negates, it's not 
     * a set in itself due to the size of that set in unicode.
     * "ej-m" implies e,j->m. e,j,k,l,m.}
     * @param set
     * {@primary set}
     * @return CharSet
     * {@primary CharSet}
     * @throws NullPointerException set[i] のどれか、または set 自身が null の場合
     * {@primary if any of set[i] is null or if set is null}
     */
    public static CharSet evaluateSet(String[] set) {
        return new CharSet(set); 
    }

    /**
     * 指定されたセットに該当する連続する文字を圧縮します。
     * 例えば squeeze("hello", "el")  
     * は(セットに含まれる l が圧縮されて) "helo" になります。
     * セットの記述方法に関しては evaluateSet に記述されている文法を参照してください。
     * {@primary Squeezes any repititions of a character that is mentioned in the 
     * supplied set. An example is:
     *    squeeze("hello", "el")  => "helo"
     * See evaluateSet for set-syntax.}
     * 
     * @param str  作業の対象となる文字列
     * {@primary the string to work from}
     * @param set  処理に使用される文字セット
     * {@primary the character set to use for manipulation}
     */
    public static String squeeze(String str, String set) {
        String[] strs = new String[1];
        strs[0] = set;
        return squeeze(str, strs);
    }

    /**
     * 指定されたセットに該当する連続する文字を圧縮します。
     * 例えば squeeze("hello", {"el"})  
     * は(セットに含まれる l が圧縮されて) "helo" になります。
     * セットの記述方法に関しては evaluateSet に記述されている文法を参照してください。
     * {@primary Squeezes any repititions of a character that is mentioned in the 
     * supplied set. An example is:
     *    squeeze("hello", {"el"&#125;)  => "helo"
     * See evaluateSet for set-syntax.}
     * 
     * @param str  作業の対象となる文字列
     * {@primary the string to work from}
     * @param set  処理に使用される文字セット
     * {@primary the character set to use for manipulation}
     * @throws NullPointerException str が null だった場合
     * {@primary if str is null}
     */
    public static String squeeze(String str, String[] set) {
        CharSet chars = evaluateSet(set);
        StringBuffer buffer = new StringBuffer(str.length());
        char[] chrs = str.toCharArray();
        int sz = chrs.length;
        char lastChar = ' ';
        char ch = ' ';
        for (int i = 0; i < sz; i++) {
            ch = chrs[i];
            if (chars.contains(ch)) {
                if ((ch == lastChar) && (i != 0)) {
                    continue;
                }
            }
            buffer.append(ch);
            lastChar = ch;
        }
        return buffer.toString();
    }

    /**
     * 指定された文字列の中にある指定された文字セット (evaluateSet を参照)
     * に該当する文字の数を返します。
     * 例えば count("hello", {"c-f","o"}) は 2 を返します。
     * {@primary Takes an argument in set-syntax, see evaluateSet,
     * and returns the number of characters present in the specified string.
     * An example would be:   count("hello", {"c-f","o"&#125;) returns 2.}
     *
     * @param str  文字の数を数える対象となる文字列
     * {@primary String target to count characters in}
     * @param set  数える文字セットを定義する文字列
     * {@primary String set of characters to count}
     */
    public static int count(String str, String set) {
        String[] strs = new String[1];
        strs[0] = set;
        return count(str, strs);
    }
    
    /**
     * 指定された文字列の中にある指定された文字セット (evaluateSet を参照)
     * に該当する文字の数を返します。
     * 例えば count("hello", {"c-f","o"}) は 2 を返します。
     * {@primary Takes an argument in set-syntax, see evaluateSet,
     * and returns the number of characters present in the specified string.
     * An example would be:   count("hello", {"c-f","o"&#125;) returns 2.}
     *
     * @param str  文字の数を数える対象となる文字列
     * {@primary String target to count characters in}
     * @param set  数える文字セットを定義する文字列の配列
     * {@primary String[] set of characters to count}
     */
    public static int count(String str, String[] set) {
        CharSet chars = evaluateSet(set);
        int count = 0;
        char[] chrs = str.toCharArray();
        int sz = chrs.length;
        for(int i=0; i<sz; i++) {
            if(chars.contains(chrs[i])) {
                count++;
            }
        }
        return count;
    }

    /**
     * 指定された文字列の中にある指定された文字セット (evaluateSet を参照)
     * に該当する文字を削除します。
     * 例えば delete("hello", {"c-f","o"}) は "hll" を返します。
     * {@primary Takes an argument in set-syntax, see evaluateSet,
     * and deletes any of characters present in the specified string.
     * An example would be:   delete("hello", {"c-f","o"&#125;) returns "hll"}
     *
     * @param str  文字を削除する対象となる文字列
     * {@primary String target to delete characters from}
     * @param set  削除する文字セットを定義する文字列
     * {@primary String set of characters to delete}
     */
    public static String delete(String str, String set) {
        String[] strs = new String[1];
        strs[0] = set;
        return delete(str, strs);
    }
    
    /**
     * 指定された文字列の中にある指定された文字セット (evaluateSet を参照)
     * に該当する文字を削除します。
     * 例えば delete("hello", {"c-f","o"}) は "hll" を返します。
     * {@primary Takes an argument in set-syntax, see evaluateSet,
     * and deletes any of characters present in the specified string.
     * An example would be:   delete("hello", {"c-f","o"&#125;) returns "hll"}
     *
     * @param str  文字を削除する対象となる文字列
     * {@primary String target to delete characters from}
     * @param set  削除する文字セットを定義する文字列の配列
     * {@primary String[] set of characters to delete}
     * @throws NullPointerException str が null の場合
     * {@primary of str is null}
     */
    public static String delete(String str, String[] set) {
        CharSet chars = evaluateSet(set);
        StringBuffer buffer = new StringBuffer(str.length());
        char[] chrs = str.toCharArray();
        int sz = chrs.length;
        for(int i=0; i<sz; i++) {
            if(!chars.contains(chrs[i])) {
                buffer.append(chrs[i]);
            }
        }
        return buffer.toString();
    }

    /**
     * 指定された文字列の中の文字の置き換えを行います。
     * 例えば translate("hello", "ho", "jy") は "jelly" を返します。
     * 置き換えられる文字の定義数が置き換える文字の定義数より大きい場合には
     * 最後に定義されている文字が使用されます。
     * {@primary Translate characters in a String.
     * An example is:  translate("hello", "ho", "jy") => jelly
     * If the length of characters to search for is greater than the 
     * length of characters to replace, then the last character is 
     * used.}
     *
     * @param target 文字を置き換える対象となる文字列
     * {@primary String to replace characters  in}
     * @param repl 置き換えられる文字を定義する文字列
     * {@primary String to find that will be replaced}
     * @param with 置き換える文字を定義する文字列
     * {@primary String to put into the target String}
     * @throws NullPointerException target、with、repl のどれかが null だった場合
     * {@primary if target, with or repl is null}
     */
    public static String translate(String target, String repl, String with) {
        StringBuffer buffer = new StringBuffer(target.length());
        char[] chrs = target.toCharArray();
        char[] withChrs = with.toCharArray();
        int sz = chrs.length;
        int withMax = with.length() - 1;
        for(int i=0; i<sz; i++) {
            int idx = repl.indexOf(chrs[i]);
            if(idx != -1) {
                if(idx > withMax) {
                    idx = withMax;
                }
                buffer.append(withChrs[idx]);
            } else {
                buffer.append(chrs[i]);
            }
        }
        return buffer.toString();
    }

}

