Finding all uppercase letters of a string in java

前端 未结 10 1118
后悔当初
后悔当初 2021-01-12 14:28

So I\'m trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:

Exception in thread \"main\" java.lan         


        
10条回答
  •  时光取名叫无心
    2021-01-12 15:22

    With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:

    Scanner in = new Scanner(System.in);
    System.out.print("Please give a string: ");
    //Uppercase
    String isUp = in.next()
            .chars()
            .filter(Character::isUpperCase)
            .collect(StringBuilder::new, // supplier
                    StringBuilder::appendCodePoint, // accumulator
                    StringBuilder::append) // combiner
            .toString();
    System.out.println("The uppercase characters are " + isUp);
    //Uppercase
    

    Inspired by:

    • Adam Bien - Streaming A String
    • Simplest way to print anIntStream as a String

提交回复
热议问题