简体   繁体   中英

How to replicate a functioning indexOf method without using indexOf in Java?

I want to find the index of certain letters in a string without using the indexOf method. I was able to do this, but I also want any letters that are not in the word/string to return a value of -1. I tried an if statement and it returns -1 as well as the index of the letter. I just want one or the other. Is there a way to do this? Thanks!

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class randomtest {
    public static void main (String args[]) {
            String text = "Cheeki Breeki";
            String letterToFind = "C";
            Pattern word = Pattern.compile(letterToFind);
            Matcher match = word.matcher(text); 
            if (!letterToFind.equals(text)) {
                System.out.println("-1");
            }

            while (match.find()) {
            System.out.println("Found letter at index "+ match.start());
        }

       } 

}

You are using the below code wrong. As String letterToFind = "C"; and String text = "Cheeki Breeki"; you are comparing these two in your if statement which will always be wrong either the character is there in string or not. because in one string you have the complete string and in another variable you have characterToFind .

if (!letterToFind.equals(text)) {
    System.out.println("-1");
}

Use the code as below, use boolean flag to check if character is found.

 public static void main(String args[]) {
        String text = "Cheeki Breeki";
        String letterToFind = "A";
        Pattern word = Pattern.compile(letterToFind);
        Matcher match = word.matcher(text);

        boolean letterFound = false;

        while (match.find()) {
            letterFound = true;
            System.out.println("Found letter at index " + match.start());
        }

        if (!letterFound) {
            System.out.println("-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