سؤال

I'm currently brushing up on my coding skills and working through some easy problems I've found online. The particular task is to input a txt file that contains any number of lines, and to have the program check each line and return "True" or "False" depending on whether that line contains all 26 letters of the alphabet. I feel like I'm almost finished, but my regular expression to match the string to [a-z] returns false no matter what I do. I've tried changing the string to lowercase, removing spaces, and nothing seems to work.

Here's a link to the project as well.

The text I have in my text file currently is "The quick brown fox jumps over the lazy dog."

package easy139;


import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;


public class easy139 {

    public static void main(String[] args) {
        try {
            Scanner in = new Scanner(new FileReader("input.txt"));
            while (in.hasNextLine()) {
                String line = in.nextLine();
                System.out.println(line);
                String noSpaces = line.replaceAll(" ","");
                if (noSpaces.matches("[a-z]")) {
                    System.out.println("True");
                }
                else {
                    System.out.println("False");
                }
            }
            in.close();
        } catch (IOException e) {
        }
    }
}
هل كانت مفيدة؟

المحلول

Your test is returning false because the regex [a-z] means "exactly one letter".

A regex that works with String.matches() is:

(?i)(?=.*a)(?=.*b)(?=.*c)...(?=.*z).*

This uses one look ahead for each letter, each of which asserts that the letter is present. The (?i) switch turns on case insensitivity.

نصائح أخرى

Here is a non regex based solution, in case you are interested in it:

public static void main(String[] args) throws Exception {
    Set<Character> letters = new HashSet<>();
    Scanner in = new Scanner(new FileReader("input.txt"));
    try {
        while (in.hasNextLine()) {
            letters.clear();
            for (char c : in.nextLine().toCharArray()) {
                if (Character.isLetter(c)) letters.add(toLowerCase(c));
            }
            System.out.println(letters.size() == 26);
        }
    } finally { in.close(); }
}

Extract this in a new method and loop over all characters:

static boolean containsAllCharacters(String line) {
    if (line.length() < 26) {
        // if string is less than 26 characters long,
        // it won't hold all characters in it
        return false;
    }

    for (char c = 'a'; c <= 'z'; c++) {
        if (line.indexOf(c) == -1) {
            return false;
        }
    }

    return true;
}

Then you can call it like:

String line = in.nextLine();
System.out.println(line);
System.out.println(containsAllCharacters(line) ? "TRUE" : "FALSE");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top