2

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Raja
  • 39
  • 3

4 Answers4

1

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;
Zixradoom
  • 917
  • 1
  • 10
  • 24
  • I used the example information given in the question, I trust the user will be able to divine the required character checking for a truly production solution. – Zixradoom May 23 '18 at 20:05
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.

Ahmad Shahwan
  • 1,662
  • 18
  • 29
1

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

AbhiCR7
  • 23
  • 2
  • 8
0

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();
}
Benjamin Caure
  • 2,090
  • 20
  • 27