If the code is something like this
const char str1[] = "abcde2fghi3jk4l";
const char str2[] = "34";
char *ret;
ret = strpbrk(str1, str2);
how should I replicate the same in Java?
If the code is something like this
const char str1[] = "abcde2fghi3jk4l";
const char str2[] = "34";
char *ret;
ret = strpbrk(str1, str2);
how should I replicate the same in Java?
There is no direct equivalent in java.
One possible solution would be the use of Pattern and Matcher.
java.util.regex.Pattern
java.util.regex.Matcher
var str1 = "abcde2fghi3jk4l";
var str2 = Pattern.quote("34");
Matcher m = Pattern.compile("["+str2+"]").matcher(str1);
if ( m.find() )
return m.start();
return -1;
First off, Java is not C and it has no pointers the same way C has.
The closest I can think of to your code is something along the lines:
final String str1 = "abcde2fghi3jk4l";
final String str2 = "34";
StringTokenizer st = new StringTokenizer(str1, str2);
String ret = st.hasMoreTokens() ? str1.substring(st.nextToken().length()) : null;
This code uses java.util.StringTokenizer, shipped with the JRE.
You can try it yourself here.
There is this function:
StringUtils.indexOfAny(String str, String searchChars)
which will return you the index of first matching character from searchChars
. Hope this is what you were looking for.
This is quite an expensive approach, see if you can use a better one.
Dependency for which is org.apache.commons:commons-lang3
There's no direct equivalent using standard API.
First solution: using Apache StringUtils library: indexOfAny()
ret = StringUtils.indexOfAny(str2,str1.toCharArray());
Second solution: using standard Java 8 API, this is quite verbose
String str1 = "abcde2fghi3jk4l";
String str2 = "34";
OptionalInt ret = str2.chars().map(c -> str1.indexOf(c)).min();
Third solution: using regex, but str1 should not contain any regex special chars so I would not recommend it ...
Matcher matcher = str2.matcher("["+str1+"]");
if(matcher.find()){
ret = matcher.start();
}