Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查字符串(单词)中是否有一个字母,以及它位于什么位置?_Java - Fatal编程技术网

Java 检查字符串(单词)中是否有一个字母,以及它位于什么位置?

Java 检查字符串(单词)中是否有一个字母,以及它位于什么位置?,java,Java,我有一个方法,一个字母(string\char?)作为参数,一次激活一个单词。我想看看这一个字母,是否在当时活跃的单词中 这本可以解释得更好。也许代码会起作用: public void checkLetter(String letter){ for(int i = 0; i<activeWord.length(); i++){ if(letter.equals(activeWord.[i])){ // Run a me

我有一个方法,一个字母(string\char?)作为参数,一次激活一个单词。我想看看这一个字母,是否在当时活跃的单词中

这本可以解释得更好。也许代码会起作用:

public void checkLetter(String letter){
        for(int i = 0; i<activeWord.length(); i++){
            if(letter.equals(activeWord.[i])){
                // Run a method which gives the user a correct letter pushed.
                }
                else {
                    String failed = "Could not find the letter in the active word.";
                    // Run a method which gives the user one wrong letter pushed.
                }
            }           
    }
公共无效校验字母(字符串字母){
对于(int i=0;i您正在寻找的:

使用
String.indexOf(String s)
,返回第一次出现的索引;如果没有找到,则使用-1

使用
String.indexOf()

这只会给出字母在字符串中第一次出现的位置。要获得其他位置,您需要从最后一个位置获取子字符串并重复此过程。

使用字符串的方法

int i = 0;
while(word.indexOf(i, letter) != -1) {
   i = word.indexOf(i, letter) + 1;
   //Do whatever
}

if(i == 0) {
   //Handle missed letter 
}

一个日常WTF启发的bruteforce正则表达式解决方案怎么样?否则只需使用String.indexOf(char)

String input=“Hello world”;
字符测试='o';
int-found=-1;
对于(int i=0;i
yourString.indexOf(yourCharacter)
?WTF Bruteforce Regex类别的月度冠军
String myString = "word";
myString.indexOf("w"); // this returns 0;
myString.indexOf("h"); // this returns -1
int i = 0;
while(word.indexOf(i, letter) != -1) {
   i = word.indexOf(i, letter) + 1;
   //Do whatever
}

if(i == 0) {
   //Handle missed letter 
}
String input = "Hello world";
char test = 'o';

int found = -1;
for (int i = 0; i < input.length(); i++) {
    StringBuilder builder = new StringBuilder();
    for (int c = 0; c < input.length(); c++) {
        if (c == i) {
            builder.append(test);
        } else {
            builder.append(".");
        }
    }
    Pattern p = Pattern.compile(builder.toString());
    if (p.matcher(input).find()) {
        found = i;
        break;
    }
}
System.out.println(found);