[英]Java equivalent for C++'s “std::string::find_first_not_of”
[英]Java equivalent for C++'s “std::string::find_first_of”
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。
最佳匹配可能是StringUtils
的IndexOfAny
方法
例;
int index = StringUtils.indexOfAny("This is a test string!", "aeiou");
不使用外部库:
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
不是最有效但最简单的:
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
字符串不得包含任何保留的正则表达式字符,例如.*[]
等。
使用番石榴 :
CharMatcher.anyOf("aeiou").indexIn("This is a test string!");
( CharMatcher
允许您比Apache StringUtils
替代方法更灵活地操作字符类,例如提供CharMatcher.DIGIT
和CharMatcher.WHITESPACE
等CharMatcher.WHITESPACE
,让您补充,联合,交叉等字符类...)
使用StringUtils.indexOfAny,这里有一个链接http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.