Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何检查字符串是否包含字母表中的所有字母?_Java_String_Arraylist - Fatal编程技术网

Java 如何检查字符串是否包含字母表中的所有字母?

Java 如何检查字符串是否包含字母表中的所有字母?,java,string,arraylist,Java,String,Arraylist,我试图检查字符串是否包含字母表中的所有字母。我创建了一个包含整个字母表的ArrayList。我将字符串转换为char数组,并遍历字符数组,对于ArrayList中存在的每个字符,我将从中删除一个元素。最后,我尝试检查Arraylist是否为空,以查看是否已删除所有元素。这表示字符串包含字母表中的所有字母 不幸的是,代码在if条件中抛出了IndexOutOfBoundsException错误,我正在从arraylist中删除元素 List<Character> alphabets =

我试图检查字符串是否包含字母表中的所有字母。我创建了一个包含整个字母表的
ArrayList
。我将字符串转换为char数组,并遍历字符数组,对于
ArrayList
中存在的每个字符,我将从中删除一个元素。最后,我尝试检查
Arraylist
是否为空,以查看是否已删除所有元素。这表示字符串包含字母表中的所有字母

不幸的是,代码在if条件中抛出了
IndexOutOfBoundsException
错误,我正在从arraylist中删除元素

List<Character> alphabets = new ArrayList<Character>();

alphabets.add('a');
alphabets.add('b');
alphabets.add('c');
alphabets.add('d');
alphabets.add('e');
alphabets.add('f');
alphabets.add('g');
alphabets.add('h');
alphabets.add('i');
alphabets.add('j');
alphabets.add('k');
alphabets.add('l');
alphabets.add('m');
alphabets.add('n');
alphabets.add('o');
alphabets.add('p');
alphabets.add('q');
alphabets.add('r');
alphabets.add('s');
alphabets.add('t');
alphabets.add('u');
alphabets.add('v');
alphabets.add('w');
alphabets.add('x');
alphabets.add('y');
alphabets.add('z');

// This is the string- I've just put a random example
String str = "a dog is running crazily on the ground who doesn't care about the world";

//Remove all the spaces
str = str.replace(" ", "");

// Convert the string to character array
char[] strChar = str.toCharArray();

for (int i = 0; i < strChar.length; i++) {

    char inp = strChar[i];

    if (alphabets.contains(inp)) {
        alphabets.remove(inp);
    }
}

if (alphabets.isEmpty())
    System.out.println("String contains all alphabets");
else
    System.out.println("String DOESN'T contains all alphabets");
List alphabets=new ArrayList();
字母。加上('a');
字母表。添加('b');
字母。加上('c');
字母。加上('d');
字母。加上('e');
字母。加上('f');
字母。加上('g');
字母。加上('h');
字母。加上('i');
字母。加上('j');
字母。加上('k');
字母。加上('l');
字母。加上('m');
字母表。添加('n');
字母。加上('o');
字母。加上('p');
字母。加上('q');
字母。加上('r');
字母表。添加('s');
字母。加上('t');
字母。加上('u');
字母。加上('v');
字母。加上('w');
字母。加上('x');
字母。加上('y');
字母。加上('z');
//这是字符串-我刚刚举了一个随机的例子
String str=“一只不关心世界的狗在地上疯狂地奔跑”;
//删除所有空格
str=str.replace(“,”);
//将字符串转换为字符数组
char[]strChar=str.toCharArray();
for(int i=0;i
列表。删除
按索引删除。由于
char
可以强制转换为int,因此有效地删除了不存在的索引值,即char'a'等于int 97。如您所见,您的列表没有97个条目

您可以执行
alphabet.remove(alphabets.indexOf(inp))

正如@trunry Wombat()和@Kevin Esche()所指出的,有更好的算法替代方案

创建

List<String> alphabets = new ArrayList <String> ();

另一个答案已经指出了例外的原因。您误用了
List.remove()
,因为它隐式地将
char
转换为
int
,称之为
List.remove(int)
,通过索引进行删除

解决这个问题的方法其实很简单。您可以让它调用
列表。通过

alphabets.remove((Character) inp);
其他一些改进:

  • 在这种情况下,应该使用
    Set
    而不是
    List
  • 您甚至可以使用
    布尔[26]
    来跟踪字母表是否出现
  • 您不需要将字符串转换为字符数组。只需执行一个
    str。charAt(index)
    将为您提供特定位置的字符
  • 使用此方法而不是
    char
    ,List remove方法有两个重载方法,一个带object,一个带int。如果传递char,它将被视为int方法

    Regex是你的朋友。无需在此处使用
    列表

    public static void main(String[] args) {
        String s = "a dog is running crazily on the ground who doesn't care about the world";
        s = s.replaceAll("[^a-zA-Z]", ""); // replace everything that is not between A-Za-z 
        s = s.toLowerCase();
        s = s.replaceAll("(.)(?=.*\\1)", ""); // replace duplicate characters.
        System.out.println(s);
        System.out.println(s.length()); // 18 : So, Nope
    
        s = "a dog is running crazily on the ground who doesn't care about the world qwertyuioplkjhgfdsazxcvbnm";
        s = s.replaceAll("[^a-zA-Z]", "");
        s = s.toLowerCase();        
        s = s.replaceAll("(.)(?=.*\\1)", "");
        System.out.println(s);
        System.out.println(s.length()); //26 (check last part added to String)  So, Yes
    
    }
    

    添加到@Leon answer中,创建一个
    列表
    并从中删除似乎是完全不必要的。您可以简单地在
    'a'-'z'
    上循环,并对每个
    字符进行检查。此外,您还将遍历整个
    字符串
    ,以了解每个字母是否都存在。但更好的版本是循环每个字母本身。这可能会在几次迭代中保护您

    最后,一个简单的例子如下所示:

    // This is the string- I've just put a random example
    String str = "a dog is running crazily on the ground who doesn't care about the world";
    str = str.toLowerCase();
    
    boolean success = true;
    for(char c = 'a';c <= 'z'; ++c) {
        if(!str.contains(String.valueOf(c))) {
            success = false;
            break;
        }
    }
    
    if (success)
        System.out.println("String contains all alphabets");
    else
        System.out.println("String DOESN'T contains all alphabets");
    
    //这是字符串-我刚刚给出了一个随机示例
    String str=“一只不关心世界的狗在地上疯狂地奔跑”;
    str=str.toLowerCase();
    布尔成功=真;
    
    对于(char c='a';c将字符串转换为小写或大写。然后循环遍历a-Z或a-Z的等效ascii十进制值,如果在字符数组中找不到,则返回false。您必须将int转换为char。

    我考虑过使用字符的ascii码

    String toCheck = yourString.toLowerCase();
    int[] arr = new int[26];
    for(int i = 0; i < toCheck.length(); i++) {
        int c = ((int) toCheck.charAt(i)) - 97;
        if(c >= 0 && c < 26) 
            arr[c] = arr[c] + 1;
    }
    
    String-toCheck=yourString.toLowerCase();
    int[]arr=新int[26];
    对于(int i=0;i=0&&c<26)
    arr[c]=arr[c]+1;
    }
    
    运行循环后,最终会得到一个计数器数组,每个计数器表示一个字母表(索引)及其在字符串中的出现

    boolean containsAlph = true;
    for(int i = 0; i < 26; i++)
        if(arr[i] == 0) {
            containsAlph = false;
            break;
        }
    
    boolean containsAlph=true;
    对于(int i=0;i<26;i++)
    如果(arr[i]==0){
    containsAlph=假;
    打破
    }
    
    所有这些解决方案似乎都为相对简单的检查做了大量工作,特别是考虑到Java 8的流API:

    /* Your lowercase string */.chars()
        .filter(i -> i >= 'a' && i <= 'z')
        .distinct().count() == 26;
    
    这样,只要
    集合
    中填充了所需的26个字符,流就会停止


    在性能方面,下面有一些(甚至还有)更有效的解决方案,但作为个人提示,我要说的是,不要让自己陷入过早优化的泥沼中,因为这样可以使您在编写实际代码时具有可读性,并且更少的努力。

    如果您喜欢像我这样的Java 8流:

    final List<String> alphabets = new ArrayList<>();
    

    这会将字符串转换为小写(如果确实只查找小写字母,请跳过),从字符串中删除所有非小写字符,然后使用并行流检查
    字母表的所有成员是否包含在字符串中。

    您可以通过更改代码中的此行来消除异常

    char inp = strChar[i];
    

    提及

    List.remove('char')
    被视为
    List.remove('int')
    ,这就是为什么会出现indexOutOfBoundsException,因为它正在检查'a'的
    ASCII
    值,该值为97。将变量'inp'转换为字符
    Set<Integer> chars = new HashSet<>();
    String s = /* Your lowercase string */;
    s.length() > 25 && s.chars()
        .filter(i -> i >= 'a' && i <= 'z') //only alphabet
        .filter(chars::add)                //add to our tracking set if we reach this point
        .filter(i -> chars.size() == 26)   //filter the 26th letter found
        .findAny().isPresent();            //if the 26th is found, return
    
    final List<String> alphabets = new ArrayList<>();
    
    final String str = "a dog is running crazily on the ground who doesn't care about the world";
    final String strAsLowercaseAndWithoutOtherChars = str.toLowerCase()
                                                         .replaceAll("[^a-z]", "");
    
    final boolean anyCharNotFound = alphabets.parallelStream()
           .anyMatch(t -> !strAsLowercaseAndWithoutOtherChars.contains(t));
    
    if (anyCharNotFound) {
        System.out.println("String DOESN'T contains all alphabets");
    } else {
        System.out.println("String contains all alphabets");
    }
    
    char inp = strChar[i];
    
    Character inp = strChar[i];
    
    static Set<Integer> alphabet = new HashSet<>(26);
    
    public static void main(String[] args) {
    
        int cnt = 0;
    
        String str = "a dog is running crazily on the ground who doesn't care about the world";
    
        for (char c : str.toCharArray()) {
            int n = c - 'a';
            if (n >= 0 && n < 26) {
                if (alphabet.add(n)) {
                    cnt += 1;
                    if (cnt == 26) {
                        System.out.println("found all letters");
                        break;
                    }
                }
            }
        }
    }
    
    public static boolean check(String input) {
      int result = 0;    
      input = input.toLowerCase();
      for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if (c >= 'a' && c <= 'z') {
          result |= 1 << (input.charAt(i) - 'a');
        }
      }
      return result == 0x3ffffff;
    }
    
    boolean check(final String input) {
        final String lower = input.toLowerCase();
        return IntStream.range('a', 'z'+1).allMatch(a -> lower.indexOf(a) >= 0);
    }
    
    sentence.split().uniq().sort() == range('a', 'z')
    
    String yourString = "the quick brown fox jumps over the lazy dog";
    
    List<String> alphabet = Arrays.asList("abcdefghijklmnopqrstuvwxyz".split(""));
    List<String> yourStringAsList = Arrays.asList(yourString.split(""));
    
    boolean containsAllLetters = yourStringAsList.containsAll(alphabet);
    
    System.out.println(containsAllLetters);