001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      https://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3;
018
019import org.apache.commons.lang3.stream.Streams;
020
021/**
022 * Operations on {@link CharSet} instances.
023 *
024 * <p>This class handles {@code null} input gracefully.
025 * An exception will not be thrown for a {@code null} input.
026 * Each method documents its behavior in more detail.</p>
027 *
028 * <p>#ThreadSafe#</p>
029 *
030 * @see CharSet
031 * @since 1.0
032 */
033public class CharSetUtils {
034
035    /**
036     * Takes an argument in set-syntax, see evaluateSet,
037     * and identifies whether any of the characters are present in the specified string.
038     *
039     * <pre>
040     * CharSetUtils.containsAny(null, *)        = false
041     * CharSetUtils.containsAny("", *)          = false
042     * CharSetUtils.containsAny(*, null)        = false
043     * CharSetUtils.containsAny(*, "")          = false
044     * CharSetUtils.containsAny("hello", "k-p") = true
045     * CharSetUtils.containsAny("hello", "a-d") = false
046     * </pre>
047     *
048     * @see CharSet#getInstance(String...) for set-syntax.
049     * @param str  String to look for characters in, may be null
050     * @param set  String[] set of characters to identify, may be null
051     * @return whether or not the characters in the set are in the primary string
052     * @since 3.2
053     */
054    public static boolean containsAny(final String str, final String... set) {
055        if (isEmpty(str, set)) {
056            return false;
057        }
058        final CharSet chars = CharSet.getInstance(set);
059        for (final char c : str.toCharArray()) {
060            if (chars.contains(c)) {
061                return true;
062            }
063        }
064        return false;
065    }
066
067    /**
068     * Takes an argument in set-syntax, see evaluateSet,
069     * and returns the number of characters present in the specified string.
070     *
071     * <pre>
072     * CharSetUtils.count(null, *)        = 0
073     * CharSetUtils.count("", *)          = 0
074     * CharSetUtils.count(*, null)        = 0
075     * CharSetUtils.count(*, "")          = 0
076     * CharSetUtils.count("hello", "k-p") = 3
077     * CharSetUtils.count("hello", "a-e") = 1
078     * </pre>
079     *
080     * @see CharSet#getInstance(String...) for set-syntax.
081     * @param str  String to count characters in, may be null
082     * @param set  String[] set of characters to count, may be null
083     * @return the character count, zero if null string input
084     */
085    public static int count(final String str, final String... set) {
086        if (isEmpty(str, set)) {
087            return 0;
088        }
089        final CharSet chars = CharSet.getInstance(set);
090        int count = 0;
091        for (final char c : str.toCharArray()) {
092            if (chars.contains(c)) {
093                count++;
094            }
095        }
096        return count;
097    }
098
099    /**
100     * Determines whether or not all the Strings in an array are
101     * empty or not.
102     *
103     * @param strings String[] whose elements are being checked for emptiness
104     * @return whether or not the String is empty
105     */
106    private static boolean deepEmpty(final String[] strings) {
107        return Streams.of(strings).allMatch(StringUtils::isEmpty);
108    }
109
110    /**
111     * Takes an argument in set-syntax, see evaluateSet,
112     * and deletes any of characters present in the specified string.
113     *
114     * <pre>
115     * CharSetUtils.delete(null, *)        = null
116     * CharSetUtils.delete("", *)          = ""
117     * CharSetUtils.delete(*, null)        = *
118     * CharSetUtils.delete(*, "")          = *
119     * CharSetUtils.delete("hello", "hl")  = "eo"
120     * CharSetUtils.delete("hello", "le")  = "ho"
121     * </pre>
122     *
123     * @see CharSet#getInstance(String...) for set-syntax.
124     * @param str  String to delete characters from, may be null
125     * @param set  String[] set of characters to delete, may be null
126     * @return the modified String, {@code null} if null string input
127     */
128    public static String delete(final String str, final String... set) {
129        if (isEmpty(str, set)) {
130            return str;
131        }
132        return modify(str, set, false);
133    }
134
135    private static boolean isEmpty(final String str, final String... set) {
136        return StringUtils.isEmpty(str) || deepEmpty(set);
137    }
138
139    /**
140     * Takes an argument in set-syntax, see evaluateSet,
141     * and keeps any of characters present in the specified string.
142     *
143     * <pre>
144     * CharSetUtils.keep(null, *)        = null
145     * CharSetUtils.keep("", *)          = ""
146     * CharSetUtils.keep(*, null)        = ""
147     * CharSetUtils.keep(*, "")          = ""
148     * CharSetUtils.keep("hello", "hl")  = "hll"
149     * CharSetUtils.keep("hello", "le")  = "ell"
150     * </pre>
151     *
152     * @see CharSet#getInstance(String...) for set-syntax.
153     * @param str  String to keep characters from, may be null
154     * @param set  String[] set of characters to keep, may be null
155     * @return the modified String, {@code null} if null string input
156     * @since 2.0
157     */
158    public static String keep(final String str, final String... set) {
159        if (str == null) {
160            return null;
161        }
162        if (str.isEmpty() || deepEmpty(set)) {
163            return StringUtils.EMPTY;
164        }
165        return modify(str, set, true);
166    }
167
168    /**
169     * Implements delete and keep.
170     *
171     * @param str String to modify characters within
172     * @param set String[] set of characters to modify
173     * @param expect whether to evaluate on match, or non-match
174     * @return the modified String, not null
175     */
176    private static String modify(final String str, final String[] set, final boolean expect) {
177        final CharSet chars = CharSet.getInstance(set);
178        final StringBuilder buffer = new StringBuilder(str.length());
179        final char[] chrs = str.toCharArray();
180        for (final char chr : chrs) {
181            if (chars.contains(chr) == expect) {
182                buffer.append(chr);
183            }
184        }
185        return buffer.toString();
186    }
187
188    /**
189     * Squeezes any repetitions of a character that is mentioned in the
190     * supplied set.
191     *
192     * <pre>
193     * CharSetUtils.squeeze(null, *)        = null
194     * CharSetUtils.squeeze("", *)          = ""
195     * CharSetUtils.squeeze(*, null)        = *
196     * CharSetUtils.squeeze(*, "")          = *
197     * CharSetUtils.squeeze("hello", "k-p") = "helo"
198     * CharSetUtils.squeeze("hello", "a-e") = "hello"
199     * </pre>
200     *
201     * @see CharSet#getInstance(String...) for set-syntax.
202     * @param str  the string to squeeze, may be null
203     * @param set  the character set to use for manipulation, may be null
204     * @return the modified String, {@code null} if null string input
205     */
206    public static String squeeze(final String str, final String... set) {
207        if (isEmpty(str, set)) {
208            return str;
209        }
210        final CharSet chars = CharSet.getInstance(set);
211        final StringBuilder buffer = new StringBuilder(str.length());
212        final char[] chrs = str.toCharArray();
213        final int sz = chrs.length;
214        char lastChar = chrs[0];
215        char ch;
216        Character inChars = null;
217        Character notInChars = null;
218        buffer.append(lastChar);
219        for (int i = 1; i < sz; i++) {
220            ch = chrs[i];
221            if (ch == lastChar) {
222                if (inChars != null && ch == inChars) {
223                    continue;
224                }
225                if (notInChars == null || ch != notInChars) {
226                    if (chars.contains(ch)) {
227                        inChars = ch;
228                        continue;
229                    }
230                    notInChars = ch;
231                }
232            }
233            buffer.append(ch);
234            lastChar = ch;
235        }
236        return buffer.toString();
237    }
238
239    /**
240     * CharSetUtils instances should NOT be constructed in standard programming.
241     * Instead, the class should be used as {@code CharSetUtils.evaluateSet(null);}.
242     *
243     * <p>This constructor is public to permit tools that require a JavaBean instance
244     * to operate.</p>
245     *
246     * @deprecated TODO Make private in 4.0.
247     */
248    @Deprecated
249    public CharSetUtils() {
250    }
251}