简体   繁体   中英

How do I use findWithinHorizon to find a letter as many times as it appears in a string?

I'm trying to create a Java program that finds a specified letter from a scanner. Can I use findWithinHorizon to do this, and if so, how?

try this

    Scanner sc = new Scanner("xxyyxxy");
    for (int n = 0;; n++) {
        String s = sc.findWithinHorizon("y", 0);
        if (s == null) {
            System.out.println(n);
            break;
        }
    }

output

3

If by scanner you mean java.util.Scanner

    public int fromScanner(Scanner scanner, String letter){
    scanner.useDelimiter(letter);
    int howMany = 0;
    while(scanner.hasNext()){
        scanner.next();
        ++howMany;
    }
    if(howMany>0)++howMany;
    return howMany;
}

There are much better ways to count a letter . Any hint of what you are doing?

EDIT here is actually using findWithinHorizon

 public int fromScanner2(Scanner scanner, String letter){ 
      int result = 0;
      String resultS = null;
      while( (resultS = scanner.findWithinHorizon(letter, 0)) !=null ){
           ++result;
      }
      return result;
 }

Now this method is a bit non-intuitive (at lest for me). When you use it and some occurrence is actually found, Scanner has internally an integer that keeps track of the position that last time was found. And on the next search it will use this postion to search starting with it

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