判断字符串是否为 Pangram 的代码?

Code to tell whether a string is a Pangram or not?

import java.io.*;
import java.util.*;


public class Solution {

    public static final int n = 26; 

    public int check(String arr) {
        if (arr.length() < n) {
           return -1;
        }
        for (char c = 'A'; c <= 'Z'; c++) {
            if ((arr.indexOf(c) < 0) && (arr.indexOf((char)(c + 32)) < 0)) {
               return -1;
            }
        }
        return 1;
    }  
}

public static void main(String[] args) {
    Scanner s1 = new Scanner(System.in);
    String s = s1.next();
    Solution obj = new Solution();

    int d = obj.check(s);

    if (d == -1) {
        System.out.print("not pangram");
    } else {
        System.out.print("pangram");
    }
}

如果输入的字符串是:
我们及时判断了下一个奖品的古董象牙带扣

它会给出错误的输出:
不是拼图

我无法找出代码有什么问题。
提前致谢!

问题是 whitespaceScanner.next() 的分隔符。因此,当您输入 We promptly judged antique ivory buckles for the next prize 时,s 将仅指向字符串 We。当您在 We 上调用 obj.check(s) 时,它将 return -1.

要验证情况是否如此,您可以打印 s 并检查其值。您还可以这样做:

String s = "We promptly judged antique ivory buckles for the next prize";

调用 obj.check(s) 并查看它将 return 正确答案。

要修复它,您应该调用 Scanner.nextLine() 而不是 Scanner.next():

String s = s1.nextLine();
import java.util.Scanner;

public class Pangrams {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int[] a = new int[26];
        int count =0;
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)>=65 && s.charAt(i)<=90){
                if(a[s.charAt(i)-65]==0)
                    count++;
                a[s.charAt(i)-65]++;
            }
            else if(s.charAt(i)>=97 && s.charAt(i)<=122){
                if(a[s.charAt(i)-97]==0)
                    count++;
                a[s.charAt(i)-97]++;
            }
        }
        if(count==26)
            System.out.println("pangram");
        else
            System.out.println("not pangram");
    }

}
May be program by using set will make solution easier ..:)


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class Pangram {

public static void main(String args[]) {

    try {
        final String str;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        str = br.readLine().toLowerCase().replaceAll(" ", "");

        char[] chars = str.toCharArray();
        final Set set = new HashSet();

        for(char c: chars){
            set.add(c);
        }

        System.out.println(set.size());
        if(set.size() == 26)
           System.out.println("pangram");
        else
            System.out.println("not pangram");

    } catch (Exception e) {
        e.printStackTrace();
    }

}

}

针对您的问题的另一个类似解决方案。

 public class PangramExample {  

      public static void main(String[] args) {  
           String s = "The quick brown fox jumps over the lazy dog";  
           System.out.println("Is given String Pangram ? : "  
                     + isPangramString(s.toLowerCase()));  
      }  
      private static boolean isPangramString(String s) {  
           if (s.length() < 26)  
                return false;  
           else {  
                for (char ch = 'a'; ch <= 'z'; ch++) {  
                     if (s.indexOf(ch) < 0) {  
                          return false;  
                     }  
                }  
           }  
           return true;  
      }  
 }  

参考,参考这个linkhttp://techno-terminal.blogspot.in/2015/11/java-program-to-check-if-given-string.html

这应该可以解决问题:

import java.io.*;        
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

        public static boolean isPangram(String test){
            for (char a = 'A'; a <= 'Z'; a++)
                if ((test.indexOf(a) < 0) && (test.indexOf((char)(a + 32)) < 0))
                    return false;
            return true;
        }

        public static void main(String[] args)throws IOException {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String test=br.readLine();
            if(isPangram(test.toUpperCase())){

                System.out.println("pangram");

            }if(isPangram(test.toUpperCase())==false){

                System.out.println("not pangram");

            }
        }
    }
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {

        String s;
        char f;
         Scanner in = new Scanner(System.in);
        s = in.nextLine();

        char[] charArray = s.toLowerCase().toCharArray();
        final Set set = new HashSet();

        for (char a : charArray) {
            if ((int) a >= 97 && (int) a <= 122) {
                f = a;
                set.add(f);
            }

        }
        if (set.size() == 26){
            System.out.println("pangram");
        }
        else {
            System.out.println("not pangram");
        }
    }
}
import java.util.Scanner;

public class Pangram {

    public static void main(String[] args) {
    int count=0;//Initialize counter to zero
    char[] arr = new char[26];//Character array of 26 size as there are 26 alphabets
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();

    for(int i= 0; i<s.length();i++)
    {
        if(s.charAt(i)>=65 && s.charAt(i)<=90)//Ascii value of A to Z(caps)
        {
            if(arr[s.charAt(i)-65]==0)
            {
                count++;
                arr[s.charAt(i)-65]=1;
            }   
        }

        if(s.charAt(i)>=97 && s.charAt(i)<=122)//Ascii value of a to z
        {
            if(arr[s.charAt(i)-97]==0)
            {
                count++;
                arr[s.charAt(i)-97]=1;
            }

        }
    }

    System.out.println(count);

    if(count==26)
    {
        System.out.println("Pangram");
    }
    else
        System.out.println("not Pangram");
    }

}

导入java.io.; 导入 java.util.;

public class 解决方案{

public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   String input = scanner.nextLine(); 
    System.out.println(isPangram(input) ? "pangram" : "not pangram"); 
}

static boolean isPangram(String input) {
    boolean isPangram = false;

    if(input == null || input.length() < 26) {
        return isPangram;
    }

    input = input.toLowerCase();
    char [] charArray = input.toCharArray();
    Set<Character> charSet = new HashSet<>();
    for(char c : charArray) {
        if(Character.isLetter(c) && (!Character.isWhitespace(c))) {
            charSet.add(c);
        }
    }
    if (charSet.size() == 26) {
        isPangram = true;
    }
    return isPangram;
}   

}

另一种方法

public boolean isPanGram(String arg)
{
    String temp = arg.toLowerCase().replaceAll(" ", "");

    String str = String.valueOf(temp.toCharArray());
    String[] array = str.split("");
    Set<String> tempSet = new TreeSet(Arrays.asList(array));
    if(tempSet.size()==26)
    {
        List loopList = new ArrayList();
        loopList.addAll(tempSet);
        if(loopList.get(0).equals("a") && loopList.get(25).equals("z"))
            return true;
    }

return false;   
}

另一个版本:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String sentence = scan.nextLine();
        sentence = sentence.toUpperCase();
        sentence = sentence.replaceAll("[^A-Z]", "");

        char[] chars = sentence.toCharArray();

        Set<Character> set = new HashSet<Character>();

        for( int i = 0; i < chars.length; i++ ) set.add(chars[i]);

        System.out.println(set.size() == 26 ? "pangram" : "not pangram");

    }
}

这里有一个更直接的方法。它还考虑了字母的重复、空格数、制表符等等。你实际上可以用实时句子来锻炼。而且如果你是新手,你不会觉得这段代码很难理解(或者我希望如此):)

import java.io.*;
import java.util.*;

public class Solution{

    static boolean check(String str){

        str=str.toUpperCase();
        int count=0;
        for(char c='A';c<='Z';c++){
            if( (str.indexOf(c)>=0) )
                count++;
        }
        if(count ==26)
            return true;
        else
            return false;
    }

    public static void main(String args[]){

        Scanner scan=new Scanner(System.in);
        String s=scan.nextLine();
        if(check(s))
            System.out.println("pangram");
        else
            System.out.println("not pangram");

    }
}
public class Panagram 
{
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("enter string ");
        String s = sc.nextLine();
        System.out.println("given string is :"+"\n" +s);
        String st=removeSpace(s);

       int d = check(st);
        if(d == -1)
            System.out.print(s+"\n" + "is not pangram");
        else
             System.out.print(s+"\n" +"is a pangram");

    }
    public static String removeSpace(String s) 
    {
        char ch[]=s.toCharArray();
        String nstr="";
        for (int i = 0; i < s.length(); i++) 
        {
            if (ch[i]!=' ') 
            {
                nstr=nstr + ch[i];
            }
        }

   return nstr;
    }

    public  static int check(String st)
    {

         int n = 26; 

        if(s.length() < n){
           return -1;   }

        for(char i = 'A'; i <= 'Z' ; i++){
            if((st.indexOf(i) < 0) && (st.indexOf((char)(i + 32)) < 0))

试一试

static String pangrams(String s) {

    String result="";
    String ls = s.toLowerCase();
    HashSet<Character> ts=new HashSet<Character>(); 
    for(int i=0;i<ls.length();i++){
        if(ls.charAt(i)!=' '){
            ts.add(ls.charAt(i));
        }
    }
    if(ts.size()==26){
        result="pangram";
    }
    else{
        result="not pangram";
    }
    return result;
}

另一个使用 HashSet 集合的简单程序。

import java.util.HashSet;

public class Panagram {

    public static void main(String[] args) {
        pangrams("qmExzBIJmdELxyOFWv LOCmefk TwPhargKSPEqSxzveiun");
    }

    static String pangrams(String s) {

        String inputString = s.toLowerCase();

        HashSet<String> toRemoveDuplicates = new HashSet<String>();
        for (String eachAlphabet : inputString.split("")) {
            toRemoveDuplicates.add(eachAlphabet);
        }

        // Total alphabets are 26 + one space, so 27.
        if (toRemoveDuplicates.size() == 27) 
            return "panagram";
         else 
            return "not panagram";
    }
}

这是一种不同的方法,但易于理解和编写。 首先删除所有 punctuation/whitespace,然后删除所有重复的字母。 最后确保修改后的字符串恰好有26个字母。

public class Pangrams {

    public static void main(String[] args) {
        String s = "The quick brown fox jumps over the lazy dog" //any text
                   .replaceAll("[^a-zA-Z]+", "") //remove all punctuation and whitespace

        if (s.length() < 1 || s.length() > 100)
            System.exit(0);

        boolean isPangram = false;
        char ch;
        String modifiedStr = "";

        //remove all duplicate letters
        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);
            if (ch != ' ') {
                modifiedStr += ch;
                s = s.replace(ch, ' ');
            }
        }

        //check whether it has exactly 26 letters
        if (modifiedStr.length() == 26) {
            isPangram = true;
            System.out.println("I am a pangram");
        }
        else System.out.println("I am not a pangram");

    }

}

plain Java for 循环检测字符串是否为 Pangram:

for (char c = 'a'; c <= 'z'; c++)
if (str.toLowerCase().indexOf(c)== -1)
    return false;