简体   繁体   中英

Reading characters in a file. By 3 at a time.... in Java

I am writing a program that needs to find the word 'the' in a given file

    while ((c=reader.read())>=0)
    {
       if (c==116 && c+1==104 && c+2==101)
        return true;
    }

This is obviously wrong, although it correctly compares the value of c against the 116 (character code of "t"), but then, c+1 is obviously not the next character in the input, so it's not comparing the right thing against 104 (character code of "h"). Ditto for c+2 and 101 (character code of "e").

How can I read through the file looking for the word 'the'?

Note that I would prefer not to use arrays or fancy libraries. How can I do this?

Reading 3 at a time will not be so easy. Consider for example the input "anthem". The first 3 characters would be "ant", the second "hem". The input contains "the", but it's split over two 3-char sequences.

It will be easier to read character by character, for example following this algorithm:

  • Read character by character with reader.read() until end of file, or until you find a t
  • Read 1 more character and check:
    • Is it end of file? -> return false
    • Is it not h ? -> continue to seek for the t
    • It's an h . Then read 1 more character and check:
    • Is it end of file? -> return false
    • Is it e ? -> return true
  • If the end of file is reached, return false

Here's one way to do it:

  boolean containsThe(Reader reader) throws IOException {
    int c1;
    while ((c1 = reader.read()) != -1) {
      if (c1 != 't') continue;

      int c2 = reader.read();
      if (c2 == -1) return false;
      if (c2 != 'h') continue;

      int c3 = reader.read();
      if (c3 == -1) return false;
      if (c3 == 'e') return true;
    }
    return false;
  }

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