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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29173540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:30:18  来源:igfitidea点击:

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

javastringjava.util.scannerpangram

提问by abh.vasishth

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");
    }
}

If the string entered is:
We promptly judged antique ivory buckles for the next prize

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

It will give the wrongoutput:
not pangram.

它会给出错误的输出:
不是 pangram

I'm not able to find out what wrong with the code.
Thanks in advance!

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

采纳答案by Anderson Vieira

The problem is that whitespaceis a separator for Scanner.next(). So when you input We promptly judged antique ivory buckles for the next prize, swill point just to the string We. When you call obj.check(s)on Weit will return -1.

问题是空格Scanner.next(). 所以当你输入时We promptly judged antique ivory buckles for the next prizes只会指向字符串We。当你调用obj.check(s)We它将返回-1

To verify that this is the case, you can print sand check its value. You can also do:

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

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

Call obj.check(s)and see that it will return the correct answer.

打电话obj.check(s)看看它会返回正确的答案。

To fix it you should call Scanner.nextLine()instead of Scanner.next():

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

String s = s1.nextLine();

回答by Mohit Motiani

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");
    }

}

回答by Ajit K'sagar

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();
    }

}

}

}

回答by satish

Another Similar Solution for your problem.

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

 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;  
      }  
 }  

for reference , refer this link http://techno-terminal.blogspot.in/2015/11/java-program-to-check-if-given-string.html

作为参考,请参阅此链接http://techno-terminal.blogspot.in/2015/11/java-program-to-check-if-given-string.html

回答by Pranav Shukla

This should fix it:

这应该解决它:

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");

            }
        }
    }

回答by JIJO T KOSHY

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");
        }
    }
}

回答by Brijesh

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");
    }

}

回答by Java Guy

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

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

public class Solution {

公共课解决方案{

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;
}   

}

}

回答by Krishna Achary

Another approach of doing this

这样做的另一种方法

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;   
}

回答by Nikola Obreshkov

Another version:

另一个版本:

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");

    }
}