简体   繁体   中英

Java:How do I make the "char" parameter into a String parameter in this specific java method?

public static int getNthOccurrence(int n, char find, String str)
    {
        int counter=0;
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i)==find)
            {
                counter++;
                if(counter==n)
                    return i;
            }
        }
        return -1;
    }

I have already seen this thread Java: method to get position of a match in a String?

The code runs that:

int n=getNthOccurrence(3,'n',"you arent gonna find me");

output: 13

Once you've changed the parameter type to String :

public static int getNthOccurrence(int n, String find, String str)

Use String.indexOf(String, int) :

i = -find.length();
for (int count = 0; count < n; ++count) {
  i = str.indexOf(find, i + find.length());
  if (i < 0) break;
}
return (i >= 0) ? i : -1;

(Note that String.indexOf(char, int) is a preferable way to do it with char , as in the case of the original code).

You can make a char into a String by simply doing this

String theString = yourChar + "";

Your code could look something like this !spoiler below!

public static int getNthOccurrence(int n, char find, String str)
    {

        String f = find + "";
        int counter = 0;

        for (String c : str.split("")){

            if (c.equals(f)) n--;
            if (n < 1 ) return counter;
            counter++;
        }

        return -1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM