Search code examples
javastringsplitsystem.out

how to delete up extra line breakers in string


I have got a text like this in my String s (which I have already read from txt.file)

 trump;Donald Trump;[email protected]    
 obama;Barack Obama;[email protected]   
 bush;George Bush;[email protected]    
 clinton,Bill Clinton;[email protected]

Then I'm trying to cut off everything besides an e-mail address and print out on console

String f1[] = null;
f1=s.split("(.*?);");
for (int i=0;i<f1.length;i++) {
       System.out.print(f1[i]);
   }

and I have output like this:

[email protected]  
[email protected]   
[email protected]  
[email protected]

How can I avoid such output, I mean how can I get output text without line breakers?


Solution

  • Try using below approach. I have read your file with Scanner as well as BufferedReader and in both cases, I don't get any line break. file.txt is the file that contains text and the logic of splitting remains the same as you did

    public class CC {
    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(new File("file.txt"));
    
        while (scan.hasNext()) {
            String f1[] = null;
            f1 = scan.nextLine().split("(.*?);");
            for (int i = 0; i < f1.length; i++) {
                System.out.print(f1[i]);
            }
        }
        scan.close();
    
        BufferedReader br = new BufferedReader(new FileReader(new File("file.txt")));
        String str = null;
        while ((str = br.readLine()) != null) {
            String f1[] = null;
            f1 = str.split("(.*?);");
            for (int i = 0; i < f1.length; i++) {
                System.out.print(f1[i]);
            }
        }
        br.close();
    }
    }