繁体   English   中英

将字符串从数组列表转换为另一个字符串

[英]Converting String from arraylist to another String

假设我有以下 Arraylist:

1. [123] [456] [789]
2. [134] [105] [455]

并且必须遵守规则:

[123] [456] = cat
[789] = dog
[134] = mouse
[105] [455] = snake

从 Arraylist 1 开始,我想形成以下新的 Array 列表:

  1. 猫狗
  2. 老鼠蛇

有没有办法做到这一点。 我目前还没有找到任何字符串到字符串转换的内容。

这里有一种方法可以做到这一点。 这只是众多可能方式中的一种; 也许还有比这更好的方法。 您可能认为这只是如何执行此操作的一个指标。 有趣的类是Rules类。 这将转换规则实现为java.util.Pattern实例,其中的apply()方法进行转换。

如果您有其他类型的输入数组而不是String ,您可以遵循一般思想,但基于Pattern的实现可能并不总是有效。

public class ListOfStringsToAnother{

    public static void main( String[] args ){
        List<String> inputStrings = getInputArray();

        List<String> output = new ArrayList<>();
        for( String input : inputStrings ) {
            output.add( Rules.INSTANCE.apply( input ) );
        }

        output.forEach( System.out::println );
    }

    private static List<String> getInputArray(){
        List<String> list = Arrays.asList( "[123] [456] [789]", "[134] [105] [455]" );
        return list;
    }

    private static final class Rules{
        static Map<String, Pattern> patterns = new HashMap<>();
        static Rules INSTANCE = new Rules();

        private Rules() {
            patterns.put( "cat", Pattern.compile( "\\[123\\] \\[456\\]", Pattern.CASE_INSENSITIVE ) );
            patterns.put( "dog", Pattern.compile( "\\[789\\]", Pattern.CASE_INSENSITIVE ) );
            patterns.put( "mouse", Pattern.compile( "\\[134\\]", Pattern.CASE_INSENSITIVE ) );
            patterns.put( "snake", Pattern.compile( "\\[105\\] \\[455\\]", Pattern.CASE_INSENSITIVE ) );
        }

        String apply( String input ) {
            /* Apply your rules here. Change this logic based on the outcome you need. */
            for( Entry<String, Pattern> e : patterns.entrySet() ) {
                Pattern p = e.getValue();
                input = p.matcher( input ).replaceAll( e.getKey() ); //This replaces the original strings in the input
            }

            return input;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM