【问题标题】:Java equivalent for C++'s "std::string::find_first_of"Java 等效于 C++ 的“std::string::find_first_of”
【发布时间】:2013-06-28 17:21:20
【问题描述】:

C++ 的“std::string::find_first_of”是否有任何 Java 等价物?

 string string1( "This is a test string!");
 int location = string1.find_first_of( "aeiou" );
 //location is now "2" (the position of "i")

实现相同功能的最简单方法是什么?

编辑:建议的解决方案也必须适用于 Android。

【问题讨论】:

    标签: java android


    【解决方案1】:

    不使用外部库:

         String string = "This is a test string!";
         String letters = "aeiou";
         Pattern pattern = Pattern.compile("[" + letters + "]");
         Matcher matcher = pattern.matcher(string);
         int position = -1;
         if (matcher.find()) {
             position = matcher.start();
         }
         System.out.println(position); // prints 2
    

    【讨论】:

    • 谢谢。我会使用这个建议,因为我不需要添加外部库。
    • @AngelKoh 另外,为了提高效率,您应该重复使用该模式,而不是每次都创建一个(当然,除非 letters 每次都更改)。
    【解决方案2】:

    不是最有效但最简单的:

    String s = "This is a test string!";
    String find = "[aeiou]";
    String[] tokens = s.split(find);
    int index = tokens.length > 1 ? tokens[0].length() : -1; //-1 if not found
    

    注意:find 字符串不能包含任何保留的正则表达式字符,例如.*[] 等。

    【讨论】:

    • 这里的快速效率改进可能是通过 2 的限制进行拆分,例如:String[] tokens = s.split(find,2);
    【解决方案3】:

    使用Guava

    CharMatcher.anyOf("aeiou").indexIn("This is a test string!");
    

    (CharMatcher 让您可以比 Apache StringUtils 替代方案更灵活地操作字符类,例如提供 CharMatcher.DIGITCharMatcher.WHITESPACE 等常量,让您对字符类进行补充、联合、相交等... )

    【讨论】:

      【解决方案4】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-03
        • 2018-08-05
        • 1970-01-01
        • 2010-09-20
        • 2010-12-08
        • 2016-02-12
        相关资源
        最近更新 更多