Search code examples
javafilejava.util.scanneruppercasereplaceall

Remove all spaces and all non-alphabet characters. Characters that are A-Z in lower case, convert them to upper case


As the title said, I want to remove all white spaces and all characters that are not A-Z. If there are lowercase characters, convert them into Uppercase. The output I want is to be: "THISISANEXAMPLEOUTPUTWITHONLYUPPERCASELETTER" How can I fix my code?

```
Here is what I have for the output right now:
 
THISISANEX
AMPLEOUTPUT
WITH
ONL
Y
UPPERCASELE
TT
E
R
123
```

---------Example file------------

  

     This is an Ex
    
    amPle       outP&ut 
    
    
    
    . WiTH 
    
    On l
    
    Y
    Uppercase Le
    
    @
    Tt
    
    E
    R
    !!!!
    123
    
    ^

My code:

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) throws FileNotFoundException {
            Scanner file = new Scanner(new File("Example.txt"));
    
            while (file.hasNextLine()) {
                String input = file.nextLine();
    
                if (!input.isEmpty()) {
                    String res = input.toUpperCase().replaceAll("\\P{Alnum}", "");
                    System.out.println(res);
                }
            }
        }
    }

Solution

  • Use the delimiter \A to read the entire file at once. To replace all non-uppercase characters, use the pattern [^A-Z].

    Scanner file = new Scanner(new File("Example.txt"));
    file.useDelimiter("\\A");
    if(file.hasNext()) {
        final String input = file.next();
        final String converted = input.toUpperCase().replaceAll("[^A-Z]", "");
        System.out.print(converted);
    }
    

    Demo!