繁体   English   中英

Java:如何在这个特定的java方法中将“char”参数变成字符串参数?

[英]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;
    }

我已经看过这个线程Java: method to get position of a match in a String?

该代码运行:

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

输出:13

将参数类型更改为String

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

使用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;

(请注意, String.indexOf(char, int)是使用char执行此操作的首选方法,就像原始代码的情况一样)。

只需执行此操作,您就可以将字符转换为字符串

String theString = yourChar + "";

您的代码可能看起来像下面这样!剧透!

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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