remington howell remington howell - 3 months ago 28
Java Question

can Java String function indexOf() look for multiple characters?

I'm trying to reduce the runtime of a program I'm working on and I want to figure out a simpler way to find the index of a character with an integer value.

At the moment, my function traces through each character of a string and returns the index of the first integer it finds. As an example, if I had the string

(yes, that's the first string I thought of), the function should return 8 because the first integer that occurs in the string, 1, is at index 8. It must first loop through each character before it to find that index, however, and that gets expensive at times.

If it helps when trying to think of an easier way to do this, I can be sure going in to the function that the format of the string will always be "[letters]" + "[numbers]" so I simply have to find the end of the (presumably random) segment of letters to get what I want.

What I would like to do is use indexOf() so I won't have to use a loop, but I do not know a way to use the function without having ten if statements (which, of course, would defeat the purpose).

Is there a way to check for multiple integers at once while using indexOf(), or some other function?


You can do this with a regex matcher.

Something like:

 Pattern pattern = Pattern.compile("\\d");
 Matcher matcher = pattern.matcher(inputString);
 if(matcher.find()) {
     return matcher.first();
 return -1;

This is fairly readable and extensible. Some might consider it overkill compared to a simple for loop through the string. Compiling the regex takes time, and you have a couple of objects created, and all this costs if you're being fanatical about performance.

 for(int i=0; i<str.length; i++) {
     char c = str.charAt(i);
     if(c >='0' && c <= '9') {
         return i;
 return -1;

Necessary, something will have to look at each character in turn, so there will be a loop somewhere, whether you write it or whether it's in the library method you call.

You might be able to squeeze some speed out of multiple cores by breaking the String into chunks and doing something map-reduce-ish. But this would only be worthwhile for really huge strings in which the digits were rare.