Karthikeyan
Karthikeyan

Reputation: 2011

finding character count between two special symbols

Am trying to find the character count between = and \n new line character using below java code. But \n is not considering in my case.

am using import org.apache.commons.lang3.StringUtils; package

Please find my below java code.

public class CharCountInLine {
    
     public static void main(String[] args) 
        {
    
     BufferedReader reader = null;
 
     try
     {
                  
         reader = new BufferedReader(new FileReader("C:\\wordcount\\sample.txt"));
          
                 
         String currentLine = reader.readLine();
         
         String[] line = currentLine.split("=");

         
         while (currentLine != null ){
             String res = StringUtils.substringBetween(currentLine, "=", "\n"); //    \n is not working.
             if(res != null) {
             System.out.println("line -->"+res.length());
             }
             currentLine = reader.readLine();
         }
         
      } 
     catch (IOException e) 
     {
         e.printStackTrace();
     }
     finally
     {
         try
         {
             reader.close();        
         }
         catch (IOException e) 
         {
             e.printStackTrace();
         }
     }
 }

}

Please find my sample text file.

sample.txt

Karthikeyan=123456
sathis= 23546
Arun = 23564

Upvotes: 0

Views: 91

Answers (2)

Robby Cornelissen
Robby Cornelissen

Reputation: 97302

Well, you're reading the string using readLine(), which according to the Javadoc (emphasis mine):

Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

So your code doesn't work because the string does not contain a newline character.


You can address this in a number of ways:

Upvotes: 4

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24593

You don't need to change how you read the lines, simply change your logic to extract the text after =.

Pattern p = Pattern.compile("(?:.+)=(.+)$");
Matcher m = p.matcher("Karthikeyan=123456");
if (m.find()) {
    System.out.println(m.group(1).length());
}

No need for Apache StringUtils either, simple Java regex will do. If you don't want to count whitespace, trim the string before calling length().

Alternatively, you can also split the line around = as discussed here.

10x simpler code:

Path p = Paths.get("C:\\wordcount\\sample.txt");
Files.lines(p)
  .forEach { line ->
    // Put the above code here
}

Upvotes: -2

Related Questions